text:
Q: Google Maps API Null Pointer Exception on GoogleMap variable Im working on an app that requires use of the Google Maps API. Ive been dealing with this problem for two days now. Im using version 2 of the API so I am using the map fragments. So, when I try to get the google map from the map fragment and assign it to my GoogleMap googleMap variable, it throws a null pointer exception. I guessing it is having trouble finding the fragment in which the GoogleMap object is stored in. Ive tried almost everything. I have tried to put the fragment in my main activity's xml file, using support map fragments, and programmatically adding the fragment into my xml file. Other problems have arose with those solution but the NPE was consistent among all of them. I feel like I am pretty close right now but I just need a little help to finally get it working.
Here is my GoogleMaps activity code:
package com.parse.starter;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.*;
import com.google.android.gms.maps.SupportMapFragment;
import com.parse.*;
import com.parse.starter.R;

import java.util.List;

public class OutbreakMap extends FragmentActivity implements LocationListener {
    double lat=50;
    double longi=50;
    private LocationManager locationManager;
    private String provider;
    private GoogleMap googleMap;
    Fragment fragment;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(isGooglePlayOn())    {
            setContentView(R.layout.map_layout);
        }
        //Add the map fragment
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragment = new com.parse.starter.MapFragment();
        fragmentTransaction.add(R.id.myfragment, fragment);
        fragmentTransaction.commit();

        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

         // Check if enabled and if not send user to the GSP settings
         // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabled) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

            // set title
            alertDialogBuilder.setTitle("Turn On Your GPS");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Please turn on your GPS to track sickness in your area!")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            OutbreakMap.this.finish();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();

        }
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {
            Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT).show();
        }

        setUpMapIfNeeded();
        googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        if(location != null)  {
            lat=location.getLatitude();
            longi=location.getLongitude();
        }

        CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(lat,longi))      // Sets the center of the map to lat,longi (which is 50,50 if the current location isnt found)
                    .zoom(17)                   // Sets the zoom
                    .build();                   // Creates a CameraPosition from the builder
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        UiSettings uiSettings=googleMap.getUiSettings();
        uiSettings.setAllGesturesEnabled(false);
        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {
        Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT).show();
        }

        ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
        ParseQuery query= new ParseQuery("Outbreak");
        query.whereWithinMiles("location",userLoc,1);
        query.findInBackground(new FindCallback() {
            public void done(List<ParseObject> objects, ParseException e) {
                if (e == null) {
                GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
                Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT).show();
                } else {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"Could Not Download Data",Toast.LENGTH_SHORT).show();
                }
            }

        });

//        moveToPrescription();
//        moveToPrescription();
    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    public void moveToPrescription(){
        Intent intent = new Intent(this,Prescription.class);
        startActivity(intent);
    }

    public void setUpMapIfNeeded() {
        if(googleMap==null) {
           googleMap= ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        }
        else {

        }
    }

    public boolean isGooglePlayOn() {
        int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(status== ConnectionResult.SUCCESS)   {
            return true;
        }
        ((Dialog) GooglePlayServicesUtil.getErrorDialog(status,this,10)).show();
        Toast.makeText(this,"Google Play Services cannot be found", Toast.LENGTH_SHORT).show();
        return false;
    }

}

Here is my xml file for my activity (the inner linear layout is the holder for the map fragment):
    <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <FrameLayout
            android:id="@+id/mapContainer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        <LinearLayout
                android:id="@+id/myfragment"
                android:layout_width="match_parent"
                android:layout_weight="4"
                android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>

Here is the xml file for the map fragment:
<?xml version="1.0" encoding="utf-8"?>

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:tag="map_fragment"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          class="com.google.android.gms.maps.MapFragment"/>

And finally here is my Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.parse.starter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
    <permission
            android:name="com.parse.starter.permission.MAPS_RECEIVE"
            android:protectionLevel="signature"/>
    <uses-permission android:name="com.parse.starter.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <!-- The following two permissions are not required to use
         Google Maps Android API v2, but are recommended. -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:name="ParseApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ParseStarterProjectActivity"

            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Register"/>
        <activity android:name=".Login"/>
        <activity android:name=".Home"/>
        <activity android:name=".OutbreakMap"/>
        <activity android:name=".Prescription"/>
        <activity android:name=".MyPrescriptions"/>
        <receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>

        <uses-library android:name="com.google.android.maps"/>
        <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="MY API KEY IS HERE"/>
    </application>
    <uses-feature android:glEsVersion="0x00020000" android:required="true"/>

</manifest>

Sorry, I dont have my LogCat dialog since it got erased and the phone I was testing on belongs to a friend who had to leave. But it basically said that there was a NPE at the line where it says setUpMapIfNeeded(); and googleMap= ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); . Also, it is worth noting that in the AndroidManifest.xml file, it says "Cannot resolve symbol '0x00020000'" where it says <uses-feature android:glEsVersion="0x00020000" android:required="true"/> at the very bottom. That doesn't stop the app from compiling and installing though. Thanks for all the help, it is very much appreciated.

A: Few things are messed up:

*

*use getSupportFragmentManager when working with FragmentActivity

*if you want to find fragment by id, then it must exists in layout file

*you want to add fragment in layout or in code (fragment = new com.parse.starter.MapFragment();) - not both

*what is com.parse.starter.MapFragment anyway?

Edit: and there are things in Manifest too...
There is probably something more, but I would suggest starting from a simple project like maps samples in google play services lib.
Edit 2: wrong things in Manifest:

*

*<uses-library android:name="com.google.android.maps"/> is unnecessary

*<uses-sdk android:minSdkVersion="4" should be 8 - probably the reason for Cannot resolve symbol '0x00020000'
You can't nest fragment inside fragment with xml. You can only instantiate nested fragment with code and use getChildFragmentManager.
I still don't see your MapFragment code, but if you really need this additional fragment, think of encapsulation: if Google's MapFragment is inside your MapFragment (would be good to change the name), then your MapFragment should be doing any interaction with nested fragment, not Activity.

A: Use getSupportFragmentManager when working with FragmentActivity
if you want to find fragment by id, then it must exists in layout file you want to add fragment in layout
or in code
(fragment = new com.parse.starter.MapFragment();)
Note: Must not use both
what is com.parse.starter.MapFragment anyway?


text:
Q: load static file with variable name in django I'm trying to do load the following static file
 img file

where image is in a for loop of images derived from a database.
But I simply got an error Could not parse the remainder: '{{' from ''static/matrices/'{{'
What should I do to fix this?  I can't use relative paths because this will be used by subsections as well, with the same html template.

A: You should avoid nesting tags.
What are you trying to solve? Isn't the image part of dynamic content? The static tag is for static content not uploaded media files.
If you must use the static tag the correct way would be something in the order of;
{% static image %} or {% static image.file %}

Depending on the object layout. If you're using an ImageField (inherits FileField) the image object already holds the path, so there's no need to manually add extensions.

A: What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.
I didn´t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.
{% for option in options_obj %}

{% endfor %}

EDIT:
Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution
{% for option in options_obj %}

{% endfor %}

A: You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.
{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
  {% static image_static %}
{% endwith %}

But in your use case it might be better if you just store the path of the images on the image model itself.

A: I got this to work by using an empty string for the static path and then using my variables in their own section, like this:
Name

A: You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:
{% load static %}
img file

or
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
img file

Reference: get_static_prefix

A: Too many quotes!
Just
img file

and you don't have to call the static in the link because you already load the static

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prevent the lp module from loading on boot? I use some software under a VMWare VM that needs to access the parallel port. If the lp kernel module is loaded, VMWare's Player can't access the port. I need to unload the module every time I want to use it under my virtual machine, and since I never use it under Ubuntu itself, it'd be nice if it was just not loaded by default.
I've tried adding blacklist lp to /etc/modprobe.d/blacklist.conf and running sudo update-initramfs -k all -u, but lsmod shows that it's still loaded after I boot. How can I keep the module from being loaded? I'm using Ubuntu 11.10 with the 3.0.0-x kernels from the kernel team PPA.

A: Building a custom kernel is not necessary
This is my procedure (legacy app, virtualized in vmware player, needing access to parallel port dongle)
in order for the parallel port dongle to work, the Ubuntu user needs to be a member of the lp group. As root (or sudo):
vigr    (add user to group lp)
vigr -s (repeat)

Next, you need to prevent the kernel module lp from loading

*

*Edit /etc/modules to ensure lp is not loaded at boot:
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.

#lp
rtc

*Blacklist lp module (Ubuntu 10 and later) to allow the player to have access to it.
Create a file: /etc/modprob.d/blacklist-vmware.conf
#/etc/modprob.d/blacklist-vmware.conf
blacklist lp

*Execute the following to update boot image:
dpkg-reconfigure linux-image-$(uname -r)

*Edit /etc/default/cups to look like this:
# Cups configure options

# LOAD_LP_MODULE: enable/disable to load "lp" parallel printer driver module
LOAD_LP_MODULE=no

Reboot and test!
lsmod | grep lp

(should be a null response)

A:
How can I keep the module from being loaded?

lp is built into the kernel, so blacklisting it won't work. The simple solution is to do rmmod lp to unload it once logged in. You can automate this by making an init script, or just putting this in your .bashrc -- use rmmod lp 2>nul so that if the module is already unloaded, it won't clutter your screen with an error.

I'm using Ubuntu 11.10 with the 3.0.0-x kernels from the kernel team PPA.

The long-term solution is to simply remove the module from the kernel, which of course requires building a custom kernel. Please see this community help page for more information on how to do this, if you choose to go this way.


text:
Q: Impersonating a thread using GSSAPI's established security context, on Windows I am working on enabling Kerberos authentication/delegation in my application.
My setup: The client is any web browser. The server runs on Windows and hosts some of my services, with Apache/Tomcat as the front end. The server can delegate work to one or more of my services on one or more machines. My services run in Java, but invoke C++ code via JNI and the C++ code makes the connection to the data sources (via ODBC for most relational data sources). Currently I am working on connecting to SQL Server via its ODBC driver.
I have mod_auth_kerb set up in Apache, and that is able to authenticate the user using Kerberos. My question: How do I use the established security context to impersonate the thread which will invoke the ODBC driver's SQLDriverConnect call? I have a working prototype that uses LogonUser and ImpersonateLoggedonUser API's to login a particular user (using her username and password) and impersonate her on the thread that invokes the  SQLDriverConnect call on the SQL Server ODBC driver. But I don't know how to use GSSAPI's established security context/delegated context (gss_ctx_id_t/gss_cred_id_t) to impersonate my thread. In other words, how do I convert the GSSAPI's handles into SSPI handles so that I can invoke ImpersonateSecurityContext or ImpersonateLoggedonUser or similar Win32 API's.
Any help would be appreciated. Thanks!
Ed


text:
Q: xcode - uploading an image with form parameters to a webserver I am tring to upload an image with 3 parameters  fror a form to a webserver unsuccessful.
My code is:
-(IBAction)uploadPhoto:(id)sender{

        NSString *urlString = @"https://urlwebservice";
        NSURL *url = [NSURL URLWithString:urlString];

        NSString *serverName = @"user";
        NSString *serverPassword = @"password";

        // create a plaintext string in the format username:password
        NSString *authStr = [NSString stringWithFormat:@"%@:%@", serverName, serverPassword];

        NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
        NSString *authValue = [NSString stringWithFormat:@"Basic %@", [Base64 encode:authData ]];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
                                                               cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval: 10];
        [request setHTTPMethod:@"POST"];
        [request setValue:authValue  forHTTPHeaderField:@"Authorization"];

        // body
        NSMutableData *postBody = [NSMutableData data];
        NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

        //image
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"item.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Type: image/jpg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        // get the image data from main bundle directly into NSData object
        NSData *imgData = UIImageJPEGRepresentation(photo, 0.2);
        // add it to body
        [postBody appendData:imgData];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"message added");
        // final boundary
        [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

        //PARAMETERS body
        NSString *nombre = @"parameter_name" ;
        NSString *valoracion = @"2";
        NSString *precio = @"12" ;

        //nombre
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[nombre dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //VAL
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[valoracion dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //PRECIO
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[precio dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        // setting the body of the post to the request
        [request setHTTPBody:postBody];

        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"RETURN from  method:   %@",returnString);

}

The equivalent java client method with a successfully response is:
  try {
                FormDataMultiPart form = new FormDataMultiPart().field("file", new File("c:\\1943.jpg"), MediaType.MULTIPART_FORM_DATA_TYPE)
                        .field("nombre", "parameter_name")
                        .field("valoracion", "4")
                        .field("precio", "13,45 €")

                WebResource webResource = Client.create().resource("https://webservice");
                webResource.header("Authorization", "Basic " + Base64.encodeBase64String(StringUtils.getBytesUtf8("user:password")));
                webResource.type(MediaType.MULTIPART_FORM_DATA)
                           .accept(MediaType.TEXT_PLAIN)
                           .post(form);

            }

Anyone know what could be my error in the objective-c code?
Thanks in advance

A: At first glance I see:
You don't send "Content-Length" of Post data.
This my working code to send image with parameters on server:
NSMutableURLRequest *myPost = [NSMutableURLRequest requestWithURL:myUrl];
[myPost setHTTPMethod:@"POST"];

NSString *stringBoundary = @"0xKhTmLbOuNdArY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
[myPost addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

for (NSString * key in postDict) {
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",[key dataUsingEncoding:NSUTF8StringEncoding]] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[postDict[key] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
if(imageData!=nil){
    [postBody appendData:[@"Content-Disposition: form-data; name=\"AVATAR_FILE\"; filename=\"test.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:imageData];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
[myPost setHTTPBody:postBody];
NSString *tmp = [NSString stringWithFormat:@"%d",[postBody length]];
[myPost setValue:tmp forHTTPHeaderField:@"Content-Length"];
[[NSURLConnection alloc] initWithRequest:myPost delegate:self];

But I recommend to use the library https://github.com/AFNetworking/AFNetworking - it is much easier and more convenient


text:
Q: draggable text box on top of canvas image hello everyone so I am trying to make a draggable text box in canvas. But when I cant seem to figure out the functionality. All I want to do is drag the text box around on top of the image. It would be really cool to just be able to click and drag the text around. Does anybody know how to do this? its becoming a headache. if you have any suggestions that'd be great.

   <canvas id="canvas" width='500' height='500' ref='canvas' @mousedown='handleMouseDown' @mouseout='resetSelectedText' @mouseup='resetSelectedText' @mousemove='handleMouseMove'></canvas>
   <input v-model="text" placeholder='type your text'>
   <button @click='addText'>
   add text
   </button>

   {{text.text}}
X

    <video id="video" ref='video' :src="source" controls="false" autoplay loop></video>

A: Dragging canvas content.
Use mousedown, mouseup, and mousemove event listeners just to update the mouse state. Eg the position and the button state.
The logic to drag rendered items should be done in the main render loop. In the example renderLoop calls handleMouse before rendering any content.
Rather than do a full VUE app example I have done the most basic text drag and drop so you can see a code example.
Drag start and drag move
In handleMouse check if mouse is down mouse.button === true

*

*if so and not dragging and there is text to drag under the mouse set dragging to true  and calculate the offset from the mouse pos to the text x, y

*"Drag" if the mouse is down and dragging true then update the selected text position by setting it to the mouse position plus the drag offset

Drag drop
If the mouse is up mouse.button === false

*

*and dragging is true then set dragging to false. The selected text item is dropped

*set selectedText to the first text item under the mouse.

Render loop
Also handles highlighting and cursors for the mouse and text to give positive feedback to the user.
Text Items
I have extended an array to handle text items. The important function is much the same as you had textItems.getUnder(point) return the text item under point.x point.y. If the point is not over a text item then the function returns undefined.
Example
As an example it may not meet all your needs, and is by no means the only way to handle drag and drop for rendered canvas content.
I hope this helps.

requestAnimationFrame(renderLoop);
const ctx = canvas.getContext("2d");
var selectedText;
const mouse = {
    x: 0,
    y: 0,
    bounds: canvas.getBoundingClientRect(),
    button: false,
    dragging: false,
    dragOffsetX: 0,
    dragOffsetY: 0,
    events(event) {  // mouse event handler should only record current mouse state
        const m = mouse;
        if (event.type === "mousedown") { m.button = true }
        else if (event.type === "mouseup") { m.button = false }
        m.x = event.pageX - m.bounds.left - scrollX;
        m.y = event.pageY - m.bounds.top - scrollY;
    }
};
document.addEventListener("mousemove", mouse.events);
document.addEventListener("mousedown", mouse.events);
document.addEventListener("mouseup", mouse.events);
function renderLoop(time) {
    if (!textItems.length) { addDemoText() }
    textItems[0].update("Frame time: " + time.toFixed(3) + "ms");
    var cursor = "default";
    handleMouse();
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    textItems.draw(ctx);
    if (selectedText) {
        cursor = mouse.dragging ? "none" : "move";
        ctx.fillStyle = "#08F"; // highlight selected text
        selectedText.draw();
    }
    canvas.style.cursor = cursor;
    requestAnimationFrame(renderLoop);
}
function handleMouse() {
    const m = mouse;
    const text = selectedText;
    if (m.button) {
        if (!m.dragging && text !== undefined) {
            m.dragging = true;
            m.dragOffsetX = text.x - m.x;
            m.dragOffsetY = text.y - m.y;
        }
        if (m.dragging) {
            text.x = m.x + m.dragOffsetX;
            text.y = m.y + m.dragOffsetY;
            text.keepOnCanvas()
        }
    } else {
        if (m.dragging) {
            selectedText = undefined;
            m.dragging = false;
        }
        selectedText = textItems.getUnder(m);
    }
}

const textItems = Object.assign([],{
    getUnder(point) { // returns undefined if no text under
        for(const t of this) {
            if (point.x >= t.x && point.x <= t.x + t.width && point.y < t.y + t.size && point.y >= t.y) {
                return t;
            }
        }
    },
    add(ctx, text, x,  y, color = "#000", size = 24, font = "arial") { // context ctx to measure the text
        var item;
        ctx.font = size + "px " + font;
        const width = ctx.measureText(text).width;
        this.push(item = {text, x, y, color, font, size, width,
            draw() {
                ctx.font = this.size + "px " + this.font;
                ctx.textBaseline = "hanging";
                ctx.fillText(this.text, this.x, this.y);
            },
            keepOnCanvas() {
                const maxX = ctx.canvas.width - this.width;
                const maxY = ctx.canvas.height - this.size;
                this.x < 0 && (this.x = 0);
                this.y < 0 && (this.y = 0);
                this.x >= maxX && (this.x = maxX - 1);
                this.y >= maxY && (this.y = maxY - 1);
            },
            update(text) {
                this.text = text;
                ctx.font = this.size + "px " + this.font;
                this.width = ctx.measureText(text).width;
                this.keepOnCanvas();
            }
        });
        return item;
    },
    draw(ctx) {
        for(const text of this) {
            ctx.fillStyle = text.color;
            text.draw();
        }
    }
});
function addDemoText() {
    var idx = 0;
    textItems.add(ctx, "", 0, 0);
    for (const t of "HI there! Some text to move with the mouse. Move mouse  over text items. Click and drag to move the text.  ".split(" ")) {
        const text = textItems.add(ctx, t, idx % (canvas.width - 80), (idx / (canvas.width - 80) | 0) * 26 + 26);
        text.keepOnCanvas();
        idx += text.width + 12
    }
}
canvas {
    border: 1px solid black;
};
<canvas id="canvas" width="600" height="180">


text:
Q: activating virtual environment using cmd but can't find the interpreter working on pyCharm, I'm activating a virtual environment using git bash, but when I want to select that specific interpreter for my python file. I can't find it in the list or may find it but still invalid.
I'm sure the venv is activated and I don't want to use the base interpreter

*

*what is the approach? starting a virtual environment using pycharm?.. or hardcoded? in my case using git bash
edit: I've added the interpreter into my interpreter's list somehow and installed some libraries- when I try to import then I get an error stating that the module isn't found

A: *

*Check the bottom right corner. There you can find the options for interpreter setting. In setting by "show all" interpreters would show you all the list.

*There you can also find the git tracker.

*In general, if you can not find something, Right top corner you can see the search icon where you can search what you are looking and you will be directed there.


text:
Q: Irreducible Polynomials over a Finite Field I am motivated by this question, and want to find a solution to the following problem.

Question: How many monic, irreducible polynomials of degree $n$ are there over the finite field $\mathbb{F}_q$ for some prime $q$?

The solution provided in the original question pivots on two central claims:
Claim 1: $\mathbb{F}_{q^n}$ is the splitting field of the polynomial $g(x)=x^{q^n}−x$
Claim 2: Every monic irreducible polynomial of degree $n$ divides $g$.
Claim 1 I am happy with, but in the case of Claim 2 I cannot see why it is true. Could someone please explain.

A: The point is that every element of ${\mathbb F}_{q^n}$ is a root of $g(x)$, so
$$g(x) = \prod_{\alpha \in {\mathbb F}_{q^n}} (x - \alpha).$$
Now an irreducible polynomial $h(x)$ over ${\mathbb F}_q$ of degree $n$ splits in distinct linear factors over ${\mathbb F}_{q^n}$, so all its factors are also factors of $g(x)$. Therefore $h(x)$ divides $g(x)$.

A: Denote by $N_q(n)$ the number of monic, irreducible polynomials in $\mathbb{F}_q[x]$ of degree $n$. Here $q$ can be any prime power. Then Claim $1$ and $2$ give
$$
q^m =\sum_{n\mid m}nN_q(n),
$$
for all $m\ge 1$, and this gives the formula
$$
N_q(n)=\frac{1}{n}\sum_{d\mid n} \mu \left(\frac{n}{d}\right)q^d
$$
by the Möbius inversion formula.


text:
Q: ¿como puedo contar el numero de veces que una clase de mi elemento html cambia? El caso es el siguiente:
Tengo 3 elementos del tipo div que hace un carousel con boostrap y en esos divs hay una clase por default que se llama item y cuando el div esta seleccionado o visible a ese item se le agrega otra clase que se llama active, lo que quiero hacer es contar las veces que cada uno de mis elementos items llegaron a contener la clase active.
Codigo html:

Aquí se genera el código de los slides con la clase item

El código html que son los divs con las clases items se generan mediante C#

A: Podes bindear el evento slid;
$('#carousel').bind('slid', function() {
    var indexSel_ = $('div.active').index() + 1;

slide

slid.bs.carousel: Occurs when the carousel has finished sliding from one item to
  another.
  slide.bs.carousel Se produce cuando el carrusel está a punto de
  deslizarse de un elemento a otro.

slide:

slide.bs.carousel Occurs when the carousel is about to slide from one
  item to another.
  slide.bs.carousel Se produce cuando el carrusel está a punto de deslizarse de un elemento a otro.

Referencia: https://www.w3schools.com/bootstrap/bootstrap_ref_js_carousel.asp


text:
Q: Parallel Programming Assignment in java I am busy on a parallel programming assignment, and I am really stuck. To be honest I am not entirely sure how each method works, but I think I have an idea.
I need to sum an array of consecutive values (in parallel). Seems easy enough, but I get 0 as an answer every time I try. I really don't know why.
class SumThreaded extends RecursiveTask<Integer> {
    static int SEQUENTIAL_THRESHOLD = 10000;
    double lo=0.0;
    double hi=0.0;

    long[] arr;

    public SumThreaded(long[] array, double a, double b) {
        arr=array;
        lo=a;
        hi=b;

    }

    public Integer compute() {

        //System.out.println(mid);
        if(hi - lo <= SEQUENTIAL_THRESHOLD) {
            int ans = 0;
            for(int i= (int) lo; i < hi; ++i)
                ans += arr[i];
            return ans;
        }
        else {
            SumThreaded left = new SumThreaded(arr,lo,(hi+lo)/2.0);
            SumThreaded right = new SumThreaded(arr,(hi+lo)/2.0,hi);
            left.fork();
            int rightAns = right.compute();
            int leftAns = left.join();
            return leftAns+rightAns;

        }
    }

    public static void main(String args[]){

        int size = 1000000;
        long [] testArray=new long[size];

        for(int i=0;i<size;i++){
            testArray[i]=i+1;
        }

        SumThreaded t = new SumThreaded(testArray,0.0,testArray.length);
        ForkJoinPool fjPool = new ForkJoinPool();
        int result =fjPool.invoke(t);
        System.out.println(result);

    }
}

Any help would be greatly appreciated.

A: Your problem appears to be that you have two separate constructors for SumThreaded, only one of which sets the class's fields. When you're feeding in the long[] array from the new in sumArray, you throw the array away. You need to pick whether you're using ints or longs (and the sum of a big array is likely to need a long) and then make sure your values are getting set appropriately. Debugging and setting a breakpoint on compute would have shown you this.


text:
Q: Flutter Stacked Widgets see-through from top widget to bottom widget Stack(
       alignment: Alignment.center,
       children: [
         ContainerA(),
         ContainerB(),
         ContainerC(),
       ],
     );

Container A contains the background gradient. Container B is a different gradient. On Container C I want to have it see-through container B and render Container A's gradient, exactly behind itself (For eg, If Container C is at a corner it should render the gradient behind that spot on Container A).
I am not talking about glass morphism, we have a lot of those on pub.dev.
How should I approach this from scratch?

A: I think flutter_mask_view or widget_mask solves the problem, maybe with some customizationit will be perfect.


text:
Q: CMake: suppress developer warnings Description:
I am using cmake-gui on Ubuntu to compile programs.
I often encountered warning messages for developpers ending by:
This warning is for project developers.  Use -Wno-dev to suppress it.

I tried to insert this -Wno-dev flag in the CMAKE_CXX_FLAGS box but it doesn't suppress the warnings.
Questions:
I have now two very simple questions:
1) Where exactly should I insert this flag?
2) How to separate it from other existing flags (if any) ?

A: Probably does not solve your problem with the gui but adding the -Wno-dev from command line works.
The flag does not belong to the CMAKE_CXX_FLAGS that are specific for compiler not for CMAKE.
Instead you can suppress the message setting the cmake_policy


text:
Q: How to use LIKE in a SQL statement to look for a number followed by the "_" character within the contents of a field? How to use LIKE in a SQL statement to look for a number followed by the "_" character within the contents of a field?
Ex: how to look for 19_  or  21_    ?
I know that _ is a reserved wildcard.... but I would need to use it here as an actual character... THANKS!!
I have a classes table. Each class has a users text field. The text field looks like this (for a record):
19_m~43~2~4-m~45~0~0-m~46~0~0-m~47~0~0-m~48~0~0-m~49~0~0-m~50~0~0-m~51~0~0-t~6~0~0-t~7~0~0-t~8~0~0-t~9~0~0-m~52~0~0-m~53~0~0-m~54~0~0-t~10~0~0-t~11~0~0-t~12~0~0-t~13~0~0|21_m~43~0~0-m~45~0~0-m~46~0~0-m~47~0~0-m~48~0~0-m~49~0~0-m~50~0~0-m~51~0~0-t~6~0~0-t~7~0~0-t~8~0~0-t~9~0~0-m~52~0~0-m~53~0~0-m~54~0~0-t~10~0~0-t~11~0~0-t~12~0~0-t~13~0~0
The user ids are the numbers that have _ after them. In this example, 19_ and 21_.
What I am trying to do is to
select * from the classes table where a certain user (number followed by _)

is present in this USERS field.
I tried something like
[...] prepare
("SELECT * from classes WHERE USERI LIKE '".$id."\\_%'")

but would not get me this record... it returns an empty result.

A: Try to use backslash:
SELECT * from classes WHERE USERI LIKE '19\_'

A: If you do not know in advance what could be the number you are looking for before the underscore, just use REGEXP.
Example: SELECT * FROM my_table WHERE field_whith_number REGEXP '^([0-9])+_';
Brief explanation of what is happening in REGEXP:
^ match the start of the line
([0-9])+ match 1 or more number
_ match a single underscore
Please note that this is not an ideal solution with very big tables since it will do a table scan.

A: If you're using SQL Server for the queries, it could be accomplished with something like
...
WHERE USERS LIKE TheID + '#_' ESCAPE '#'

The ESCAPE after LIKE designates an escape character which can be used to specify special characters as literals.


text:
Q: c# System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string From package manager console in visual studio 2022 whenever I am running below migration command
Add-Migration AddtableCampaign
following error ocurrs
System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string.
Parameter name: startIndex
   at System.String.Substring(Int32 startIndex, Int32 length)
   at System.Data.Entity.Migrations.History.HistoryRepository.GetPendingMigrations(IEnumerable`1 localMigrations)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.ScaffoldInternal(String name, DbConnectionInfo connectionInfo, String migrationsConfigurationName, Boolean ignoreChanges)
   at System.Data.Entity.Infrastructure.Design.Executor.Scaffold.<>c__DisplayClass0_0.<.ctor>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
   at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
startIndex cannot be larger than length of string.
Parameter name: startIndex

I am running simple entity framework migration command but cannot find the problem for this solution


text:
Q: Copy multiple shapefiles that intersect a polygon to a new location I am trying to select and copy shapefiles from one folder to a new location based on if they intersect a polygon feature class. I am getting stuck in somewhere in the for loop.
EDIT: The goal is to copy the whole file if the extent of the shapefile intersects the polygon. I am not wanting to copy a subset of any shape.
# Generate list of shapefiles in the workspace
# Copy shapefiles in a list that intersect a polygon to a new location

import arcpy
import os

# set environment settings
arcpy.env.workspace = 'E:\\workspace\\Contour_Shapefile'

# set local variables
out_workspace = 'C:\\localvariables\\outworkspace\\'
select_features = 'C:\\localvariables\\Project.gdb\\AreaOfInterest'

# use ListFeatureClasses to generate a list of shapefiles in the workspace shown above.
fc_list = arcpy.ListFeatureClasses()

#Execute CopyFeatures for each input shapefile that INTERSECT Area of interest.
i=1
for shapefile in fc_list:
    out_featureclass = os.path.join(out_workspace, os.path.splitext(shapefile)[0])
    arcpy.SelectLayerByLocation_management(shapefile, 'INTERSECT', select_features)
    arcpy.CopyFeatures_management(shapefile, out_featureclass)
    print(str(i) + ' copied ' + shapefile)
    i += 1
else:
    print( str(i) + ' MISSING')
    i += 1
inpfile.close()

A: I see the very last line as error-ing out as inpfile is not defined anywhere. You also didn't store the selection set as a variable or test whether the returned selection layer had any records before copying.
try this.
# Generate list of shapefiles in the workspace
# Copy shapefiles in a list that intersect a polygon to a new location

import arcpy, os

# set environment settings
arcpy.env.workspace = 'E:\\workspace\\Contour_Shapefile'

# set local variables
out_workspace = 'C:\\localvariables\\outworkspace\\'
select_features = 'C:\\localvariables\\Project.gdb\\AreaOfInterest'

# use ListFeatureClasses to generate a list of shapefiles in the workspace shown above.
fc_list = arcpy.ListFeatureClasses()

#Execute CopyFeatures for each input shapefile that INTERSECT Area of interest.
for shapefile in fc_list:
  #create output feature class
  out_featureclass = os.path.join(out_workspace, os.path.splitext(shapefile)[0])
  #create selection layer in memory
  selection = arcpy.SelectLayerByLocation_management(shapefile, 'INTERSECT', select_features)
  #retreieve record count of selection
  selectionCount = int(arcpy.management.GetCount(selection)[0])
  #print shapefile and record count
  print(f"Selection Shapefile: {shapefile}; Record Count: {selectionCount}")
  #if selection contains records, copy feature
  if selectionCount > 0:
  #on the following line, if you replace 'shapefile' with 'selection' it will copy just the intersecting features.
    arcpy.CopyFeatures_management(shapefile, out_featureclass)
    print(f"Copied Shapefile: {shapefile}")
  else:
    print(f"Skipping shapefile -> {shapefile}")

I stored your selection layer as a variable, tested the selection layer to see if there were records, and if there were more than 0 records in the selection layer, copied the layer into the new directory. This has f-string formatting, so you may need to comment out my print statements if using an older version of python. There are also comments on each line explaining what I did. If you need more help or this doesn't work let me know and let's see if we can't figure it out!
EDIT: this can also be done with the Arcpy Geometry Class. Look at the "disjoint" and "distanceTo" methods. Disjoint returns false if 2 geometries intersect, and distanceTo returns the minimum distance between two objects (returns 0 if they intersect)
https://pro.arcgis.com/en/pro-app/latest/arcpy/classes/geometry.htm


text:
Q: How to reverse map of objects to vector of tuples by using an iterator? What is the easiest way to convert HashMap<String, String> to Vec<(String, Vec<String>)> by using an iterator ? I want to reverse the map.
I've tried to use iter() methods but have no idea how to do a correct map closure implementation for collecting values after:
fn get_aliases(&self) -> Vec<(String, Vec<String>)> {
    let mut aliases: HashMap<String, String> = HashMap::new();
    aliases.insert("a".to_owned(), "test".to_owned());
    aliases.insert("b".to_owned(), "test".to_owned());
    aliases.insert("c".to_owned(), "test2".to_owned());

    aliases.iter().map(|(ref a, ref c)| {
        // what to do here?
    }).collect()

    // the expected return value is:
    // [("test", ["a", "b"]), ("test2", ["c"])]
}

This function will return a vector which says what String keys belong to some object.
I could write a lot of code with for and finds but it seems to me this would be less efficient and I think there is a way to do that by using iterators only.

A:
I could write a lot of code with for and finds but it seems to me this would be less efficient and I think there is a way to do that by using iterators only.

I wouldn't call it a lot of code, and remember that for loops operate on iterators. I've not done any benchmarking, but this is far simpler and I'd expect it to be more performant:
use std::collections::HashMap;

fn get_aliases(aliases: HashMap<String, String>) -> Vec<(String, Vec<String>)> {
    let mut x = HashMap::new();

    for (k, v) in aliases {
        x.entry(v).or_insert_with(Vec::new).push(k)
    }

    x.into_iter().collect()
}

fn main() {
    let mut aliases = HashMap::new();
    aliases.insert("a".to_owned(), "test".to_owned());
    aliases.insert("b".to_owned(), "test".to_owned());
    aliases.insert("c".to_owned(), "test2".to_owned());

    println!("{:?}", get_aliases(aliases));
}

A: It's not trivial, certainly not as trivial as it would be with some other stream libraries that provide the necessary functions.
You can use the itertools crate's group_by to group elements by some key. However, it only groups adjacent elements, so you have to sort them first. Here's my result:
impl A {
    pub fn get_aliases(&self) -> Vec<(String, Vec<String>)> {
        // Get a Vec of string references for sorting. Reverse element
        // order for clarity.
        let mut v = self.aliases.iter()
            .map(|(a, c)| (&c[..], &a[..])).collect::<Vec<_>>();
        v.sort_by_key(|t| t.0); // Make identical keys adjacent.
        let g = v.into_iter().group_by(|t| t.0); // Create grouping.
        g.into_iter()
            .map(|(key, group)| // key is the str with the key
                                // group is a subiterator that just visits
                                // elements with that key, Item=&(&str,&str)
                (key.to_string(), // result is a tuple of the key as String
                 group.map(|t| t.1.to_string()).collect())
                   // and the subiterator turned into a Vec<String>
                )
            .collect() // finally, turn Iterator<Item=(String, Vec<String>) into Vec
    }
}

Going back to your original problem, you have the additional issue that Arc<Object> is only PartialEq (needed by group_by) if Object is; same for Ord (needed by sort_by_key). If your Object type cannot be compared that way and you want to use the pointer identity, your intermediate vector will need to store some newtype wrapper around Arc that uses pointer values for comparison.


text:
Q: Dependency injection in angular hybrid app (AngularJS & Angular 5) I've got a problem with dependency injection in ngUpgraded AngularJS controller. I'd like to use toastr and Handlebars.js module in my hybrid app, but my every attempt to do it gives me erros (handlebars is necessary to handle external scripts from server side written long time ago, that's why I need to use this some antipattern solution). The last script (providers) works only for jQuery usage.
AngularJS controller:

    export const dataVisualization = {
        selector: 'dataVisualizationNgJs',
        templateUrl: './data-visualization-ngjs.template.html',
        bindToController: {
            data: '='
        },
        controller: ['$scope', '$timeout', ($scope, $timeout) => {
          ....
       }
    Directive({
        selector: dataVisualization.selector
    })
    export class DataVisualizationFacade extends UpgradeComponent {
        @Input() data: any;

        constructor(elementRef: ElementRef, injector: Injector) {
            super(dataVisualization.selector, elementRef, injector);
        }
    }

AngularJS module:

    export const ngjsModule = angular.module('dataVisualizationNgJs', [])
        .component(dataVisualization.selector, dataVisualization).directive(DataVisualizationComponent.selector, downgradeComponent({
            component: DataVisualizationComponent,
        }) as angular.IDirectiveFactory);

Angular 5 module:

    @NgModule({
        declarations: [
            DataVisualizationComponent,
            DataVisualizationFacade,
        ],
        entryComponents: [
            DataVisualizationComponent
        ],
        imports: [
            NgbModule,
            GatewaySharedModule,
            RouterModule.forChild(DataVisualizationRoute),
            FormsModule,
            UpgradeModule,
        ],
        providers: [
            jQueryProvider,
            toastrProvider,
            handlebarsProvider,
            {
                provide: '$scope',
                useFactory: (i) => i.get('$rootScope'),
                deps: ['$injector']
            }
        ]
    })

    export class DataVisualizationModule {
    }

Angular 5 providers:

    export const JQUERY_TOKEN = new InjectionToken('jQuery');

    export const jQueryFactory = () => {
        return $;
    };

    export const jQueryProvider = {
        provide: JQUERY_TOKEN,
        useFactory: jQueryFactory
    };

    export const TOASTR_TOKEN = new InjectionToken('toastr');

    export const toastrFactory = () => {
        return toastr;
    };

    export const toastrProvider = {
        provide: TOASTR_TOKEN,
        useFactory: toastrFactory
    };

    export const HANDLEBARS_TOKEN = new InjectionToken('Handlebars');

    export const handlebarsFactory = () => {
        return Handlebars;
    };

    export const handlebarsProvider = {
        provide: HANDLEBARS_TOKEN,
        useFactory: handlebarsFactory
    };


text:
Q: How can I find the index of the last item in an array? My Array:
(rdb:381) pp params[:payments]
{"0"=>{":amount_paid"=>"100.00", ":date_paid"=>"2/27/2008"},
 "1"=>{":amount_paid"=>"80.00", ":date_paid"=>"3/27/2008"},
 "2"=>{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}}

I don't believe this is an object . Performing params[:payments].last returns this :
NoMethodError Exception: undefined method `last' for #<ActiveSupport::HashWithIndifferentAccess:0x1065e8448>

I am trying to find the index of that last item. In this case, the answer is 2, or "2"

A: Hey, your array is actually a hash.  You could maybe get the index of the last key by doing something like params[:payments].keys.map(&:to_i).max.to_s
It would be even better to pass an actual array back.  How are you generated the :payments option?

A: Your value is a Hash, not an Array, so it doesn't have ordering or indexes, unless you are on Ruby 1.9


text:
Q: Deferred scripts and DOM I need to run script only when DOM is ready as script does some rewriting of certain attributes of certain tags.
Currently I use document.addEventListener on DOMContentLoaded or if not available document.attachEvent  on onreadystatechange and if both not given I use window.onload functionality.
I read about defer tag for scripts that should be executed after document is parsed.

*

*Does this mean that by setting defer attribute I can easily execute my script when DOM is ready?

*Is there some hidden stuff I may miss?

*How well is supported i.e. Opera, WebKit, Firefox, IE?

Edit: I'm aware of libraries like JQuery but I can't use them as I need very small script so I need a low level solution.

A: A proper implementation of the defer attribute will automatically run the script after the DOM has finished parsing so any code in the script does not have to do it's own logic for when the DOM is loaded.  You can read this Mozilla article for more details.
However, the defer attribute is not supported in all older browsers so you have to decide what browsers you want to support and what your strategy is for any that don't support defer.  You can read the history of browser implementation in this SO post.  In a switcheroo, it was implemented first in IE, then in Firefox, then in Safari and Chrome.  Judging by the dates/versions in that post, it looks like it's pretty safe to rely on it now except for Opera, but you'll have to dive into the details in that post to be sure it meets your requirements.
Here's a chart that shows browser support for defer: http://caniuse.com/script-defer.
As best I can tell, the main controversy with defer is whether multiple defer scripts execute in order or not (they are supposed to execute in order) and how they interact with scripts that use async.  The standards and implementations are now clear, but were not always.  But, if you just have one stand-alone defer script that you only care about executing after the DOM is parsed, you should be safe.

A: If you are amenable to using JQuery ( http://jquery.com/ ) then you can use:
$(document).ready(
    function(){
    //do something here, the DOM is ready!
    }
);

For the full details visit http://api.jquery.com/ready/
The .ready function will load after the DOM is ready and I believe (though I could be mistaken) that the JQuery team have largely taken care of anything which you (or I) might miss.
While you can tackle this without the overhead of JQuery, in my (novice) experience, the headache isn't worth the hassle. Also, JQuery has a lot of other nifty tools too. :)


text:
Q: Calendar setup doesnt work I had been trying for a while to make a "Calendar" that schedule from the current day to the same day next week, but so far everything I tried failed.
cal = Calendar.getInstance();

switch (day) {
case 1:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    break;
case 2:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
    break;
case 3:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
    break;
case 4:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
    break;
case 5:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
    break;
case 6:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
    break;
case 7:
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    break;
}
cal.set(Calendar.HOUR_OF_DAY, hrs);
cal.set(Calendar.MINUTE, mins);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

This works for some of the days, for the rest the time is set backwards, or better said,
for exp. taking the today's day 6/4/2014 ->
Jun 2, Mon ...
Jun 3, Tue ...
Jun 4, Wen ...
Jun 5, Thu ...
Jun 6, Fri ...
Jun 7, Saturday ...
Jun 1, Sunday ...
Any ideas how to set proper calendar that sets the time forwards, not backwards?


text:
Q: Single Page loader PDF reader in PHP / Ruby / .NET I've very large sized PDF files. I want a PDF reader (PHP / Ruby / .NET) that does not load the whole file but just the page so that the response time gets better.
There are many PHP and .NET PDF readers but I'm not sure if they just load a page or load the whole file at once.


text:
Q: 3D animation with bones and their matrices I really am asking this as a last resort. I haven't been able to solve this for 2 days now. So if someone knows a thing or two about 3D, Matrices and animation I would really appreciate your input.
I have downloaded this project and implemented it into my own project: http://xbox.create.msdn.com/en-US/education/catalog/sample/skinned_model.
The character in my game move his hands as he casts a spell. I have successfully made this animation and imported it into the project. But I need to spawn particles inside the palms of his hands which move according to an animation. All I need is the 3D position of the palms of his hands after the animation has been applied.
Picture of hands during the animation:
http://s18.postimg.org/qkaipufa1/hands.png
If you take a look at the skinned model sample project: Class: AnimationPlayer.cs you will notice that it processes the matrices 3 times:
    public void Update(TimeSpan time, bool relativeToCurrentTime,
                       Matrix rootTransform)
    {
        UpdateBoneTransforms(time, relativeToCurrentTime);
        UpdateWorldTransforms(rootTransform);
        UpdateSkinTransforms();
    }

And allows us to access them after each of the steps:
        /// Gets the current bone transform matrices, relative to their parent bones.
    /// </summary>
    public Matrix[] GetBoneTransforms()
    {
        return boneTransforms;
    }

    /// <summary>
    /// Gets the current bone transform matrices, in absolute format.
    /// </summary>
    public Matrix[] GetWorldTransforms()
    {
        return worldTransforms;
    }

    /// <summary>
    /// Gets the current bone transform matrices,
    /// relative to the skinning bind pose.
    /// </summary>
    public Matrix[] GetSkinTransforms()
    {
        return skinTransforms;
    }

I should also mention that I know the index of the bone in the palm and the index of all its parents:
10 - 11's parent, Root bone
11 - 12's parent
12 - 13's parent
13 - 14's parent
14 - 15's parent
15 - 16's parent
16 - The bone in the palm
As far as I understand this project is that all of the GetXXXXXXXX Commands I listed above return an array of Matrix[] ordered according to the index of the bone. So to get the Transform of Bone 10. I believe the code will look like:
Matrix[] M = animtionplayer.GetSkinTransforms();
Matrix transform = M[10];

OK, now for the parts I don't understand.
I don't know which of the 3 GetXXXXXXXXX functions I need to use to get the palms position.
I think the way the shaders calculate the position of the bones is by multiplying them by each of their parent bones. So:
Matrix[] M = animtionplayer.GetBoneTransforms();
Matrix transform = M[10];
transform = transform * M[11];
transform = transform * M[12];
transform = transform * M[13];
transform = transform * M[14];
transform = transform * M[15];
transform = transform * M[16];
//maybe apply the world position of the model?
transform = transform * MyWorld;

And then maybe to get a vector3 position.
Vector3 HandPosition = transform.Up;

Well when I try the solution above I get mixed results. With certain bones it moves correctly for the middle section of the animation. But honestly nothing good. Can someone explain whats going on here? How do I get the position of the bone in the palm? I'm really in the dark here. I only learnt what a matrix was 2 months ago, and animation with bones only this week.

A: Alright so this bug was quiet frustrating so I took a break from coding for about a week. I started working on it again 2 days ago. Trying many random things.... looking at the values of the matrices looking for patterns and I finally got it.
Here is an image where the hands are animated and all the bones are highlighted perfectly with big white spheres. And it follows the animation perfectly too!
http://s27.postimg.org/f48i7ae4x/2014_07_30_18_H14_M20_S.jpg
The code:
Matrix[] BoneTransforms = animtionPlayer.GetWorldTransforms();
for (int i = 0; i < BoneTransforms.Length; i++)
{
    Vector3 v3 = new Vector3(BoneTransforms[i].M41, BoneTransforms[i].M42, BoneTransforms[i].M43);
    v3 = Vector3.Transform(v3, GetWorld(Position, Rotation, Scale));//GetWorld is the models world matrix: position, rotation and scale.
    Game1.DrawMarker(v3); //v3 is the position of the current Bone.
}

I just made that code by watching all of the values of the specific Matrix. I learnt that M41, M42, M43 are the X, Y, Z cords from the specific bone.

A: Reopen your mesh designer, put an empty in his hands about where the particle effect should be, parent the empty to the "palm" bones and keep track of what direction in local coords the empty is facing so you can face the particles in the right direction, rebake the animation and reimport it.  I will admit I'm not familiar with the "mesh skinner" you're using - but I would imagine it supports child objects of bones like empties as they're frequently employed for such purposes.  You're overthinking this.  If you can't do this with the X-box kit, I don't know.
A "transform matrix" isn't necessarily the location of the bone - so I'm confused about what these functions return.  They probably just return the matrix it uses to calculate the position of the vertices which are weighted to those bones.  There isn't a function to return the "world position" of a palm bone and simply track your animation to the world position of the empty or palm bone?  I'm confused what you need to use the transform matrices for.  If the library you're using is good, there will almost certainly be a way to get a bone's world coordinate in which case adding a "tracking bone" just outside the palm will let you track animations or objects to that bone or even directly parent them.


text:
Q: Wordpress Admin Ajax call I'm trying to do a simple dashboard widget where the user can see posts with status 'pending' and from there either approve or remove them. For this I obviously need to do an ajax call and use hooks to work it into WP. This is what I've got so far:
// admin area ajax function
add_action('admin_head', 'my_action_javascript');

function my_action_javascript($action) {
    ?>

     <?php
}

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    $action = $_POST['action'];
    $postid = $_POST['postid'];

    switch($action) {
            case 'approve_post':
                $mypost = array();
                $mypost['ID'] = $postid;
                $mypost['post_status'] = 'publish';
                wp_update_post($mypost);
            break;

            case 'delete_post':
                wp_delete_post($postid);
            break;
     }
     die();
}

Code is taken from the example from the wordpress codex.
The links i refer to in my jQuery looks like this:
Delete

I've checked in the click function that the id and class transfered is correct.
The response i get from the ajax call is '0', which according to the codex means it was successful, but nothing happens. The post doesn't get deleted when I press delete, and it doesn't change post_status when I click approve.
What am I doing wrong here?
// Cheers


text:
Q: mongodb-es6 promise not working I am playing around mongodb-es6-master, in which it was written that mongoClient.connect() returns a promise, but i am not able to invoke the 'then' function on that promise.
i have a file named index.js
which i am invoking with node version 5.0.
following is the code snippet. Am i missing anything?

    'use strict'
    var co = require('co');
    var MongoClient = require('mongodb-es6').MongoClient;
    co(function* (){
    let client = yield new MongoClient("mongodb://localhost:27017/test",            {}).connect();

    var collectionP = yield client.then((value) => {
    //some code
    //    console throws  [TypeError]client.then in not a function


text:
Q: REGEX to select CSS Classes names from file I need to select all classes names in a css file, I am just new at it, also if someone can advice some good online tutorials for regex is appreciated.
Regex will be used in JavaScript
I came with this which works for simple classes:
/(?<=\.).+?(?=\{)/g
.className {
}

the above regex returned this: className
now I need to add for this too:
tagName1 {
}

#tagName2 {
}

.tagName3:hover {
}

.tagName4:anything {
}

should result in:
tagname1
tagname2
tagname3
tagname4

So how to select the above ones?

A: My guess is that, we would want to design an expression similar to,
([^:#\s.]+)(?:.*?)?\s*({[^}]*?})

where in this capturing group,
([^:#\s.]+)

we would deselect some chars such as ., # and space, and we'd collect our desired data.
Demo

A: I'd use:
 ^[.#]?(\w+)(?=(?::\w+)?\s*{)

The wanted name is in group #1
Demo with javascript regex flavour.


text:
Q: Load JavaScript into a page I do not own before any of its JavaScript executes I have found a web page I don't have control over. I can see in its console that it is throwing a "missing jQuery" error from its Bootstrap script.
I'd like to load jQuery before this script executes when I navigate to this page so I can see if the site operates differently.

A: TL;DR
Yes, it's possible, but not the conventional way
Why no
You can't run Javascript on arbitrary Web pages that you do not control the content of. It would be a huge security hole if that were not true.
Think about it: you could run Javascript and wait for someone to log on to their internet banking and then do something with the characters input.
Why yes
However, if you just want to get the page working, you can use Tampermonkey. You can use it to execute custom scripts on page load for any website you want. You can find some basic tutorials here: https://hibbard.eu/tampermonkey-tutorial/


text:
Q: Have issue with JSON I have an issue with json parsing
-I established a connection to a remote server to receive a json object, which looks like this
2011-08-31 13:23:27.280 WallpaperBackground[731:40b] jsonString:{"photoset":{"id":"72157627554107638", "primary":"6095921496", "owner":"66801517@N05",  "ownername":"Gariya1", "photo":[{"id":"6096223569", "secret":"47081ffe65", "server":"6202", "farm":7, "title":"snakc", "isprimary":"0"}, {"id":"6095921496", "secret":"ea3b2b5076", "server":"6064", "farm":7, "title":"images", "isprimary":"1"},

-In the didReceiveData method, I assigned the json string
code:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

then I built my dictionary
code:
NSDictionary *results = [jsonString JSONValue];

when i am runing this, In console i am getting these error
 2011-08-31 13:23:27.284 WallpaperBackground[731:40b] -JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \"Unescaped control character '0x0'\" UserInfo=0x4e1d670 {NSLocalizedDescription=Unescaped control character '0x0'}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: server\" UserInfo=0x4e1d7c0 {NSUnderlyingError=0x4e1d6d0 \"Unescaped control character '0x0'\", NSLocalizedDescription=Object value expected for key: server}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Expected value while parsing array\" UserInfo=0x4e1d810 {NSUnderlyingError=0x4e1d7a0 \"Object value expected for key: server\", NSLocalizedDescription=Expected value while parsing array}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: photo\" UserInfo=0x4e1d8d0 {NSUnderlyingError=0x4e1d890 \"Expected value while parsing array\", NSLocalizedDescription=Object value expected for key: photo}",
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: photoset\" UserInfo=0x4e1d980 {NSUnderlyingError=0x4e1d8b0 \"Object value expected for key: photo\", NSLocalizedDescription=Object value expected for key: photoset}"

If any one knw let me help out pl... thanx

A: The connection:didReceiveData: method will be called multiple times as parts of the data are loaded. You cannot assume that the data is complete until connection:didFinishLoading: is called. Until then, you have to concatenate the chunks of data in a buffer (like NSMutableData).

A: Instantiate a NSMutableData, preferably public in your interface definition found in your .h file.
Every time connection:didReceiveData: is called, use the NSMutableData's "appendData:data" method to add the newly received data to the variable.
When your connection:didFinishLoading: method is called, you will have a completely filled NSMutableData object waiting to be parsed.
Then call the SBJSONParser's method to parse it like you did.
EDIT
You declare a NSMutableData object in your .h file.
Whenever your connection object calls its delegate method DidReceiveData you will append the data as follows:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [publicDataObject appendData:data];
}

When the data is completely downloaded you will be left an object with your complete data in it.
So then in your finishedLoading method:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *jsonString = [[NSString alloc] initWithData:publicDataObject encoding:NSUTF8StringEncoding];

    id results = [jsonString JSONValue];
}

If you know for sure what the resulting datatype will be you can change the datatype of the results variable from id to i.e. NSDictionary, or NSArray.
Hope this helps.


text:
Q: Fetching results from Celery backend is abnormally slow I'm using Celery with a Redis broker to do some "heavy" processing for my Django app. Everything is running locally in Docker containers on WSL2.
The tasks output a JSON which is roughly 2.5 Mb large and it takes up to 9 seconds to retrieve the result via get() in the Django app. For smaller payloads, the time goes down
I tried increasing the RAM and the CPU for WSL2 up to 6 CPUs and 8Gb RAM. Celery was configured with --max-memory-per-child=1024000 --concurrency=4
I've tried using different result_backend configuration with similar results:

*

*Redis

*RPC

*SQLite with SQLAlchemy

I tried setting an interval when using SQLite (doesn't matter for RPC & Redis) with a 0.5sec improvement get(interval=0.01)
I also tried changing the result_serializer from JSON to pickle for poorer performance. But I don't think the serializer is the culprit here as serializing / deserializing the same JSON is pretty fast in console
>>> timeit.timeit(lambda: pickle.dumps(big_dict,0), number=10)
0.567067899999528

>>> timeit.timeit(lambda: pickle.loads(str), number=10)
0.3542163999991317

I tried using compression, only zlib seemed to provide a small gain.
I'm not too familiar with this setup but IMHO I should be able to retrieve results faster. The best I could achieve was 6sec. Any idea how to improve this or how to explain it ?
settings.py
CELERY_BROKER_URL = "redis://{host}:{port}/{db}".format(
    host=os.environ.get('REDIS_HOST'),
    port=os.environ.get('REDIS_PORT'),
    db=os.environ.get('CELERY_REDIS_DB')
)
CELERY_RESULT_BACKEND = "redis://{host}:{port}/{db}".format(
    host=os.environ.get('REDIS_HOST'),
    port=os.environ.get('REDIS_PORT'),
    db=os.environ.get('CELERY_REDIS_DB')
)
# CELERY_RESULT_BACKEND = 'db+sqlite:///celery.sqlite'  # SQL Example (need SQLAlchemy==1.4.29 in requirements.txt)
# CELERY_RESULT_BACKEND = 'rpc://localhost'  # RPC Example
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

Thanks

A: In general, Redis has a reputation for being bad at dealing with large objects and is not generally intended to be a large object store.  You're better off using a general purpose RDBMS or a file store and returning a key to where the JSON can be retrieved.


text:
Q: Angular build error in core/src/render3/interfaces While building an Angular 6 app i get a compile error in @angular/core/src/render3/interfaces on line 35. The line is:
   [ACTIVE_INDEX]: number | null;

and the error is:
error TS1169: A computed property name in an interface must directly refer to a built-in symbol.
I an using @angular/core@6.1.6. Am I doing something wrong or is this an Angular bug?

A: Verify that Visual Studio is targeting the correct version of Typescript (as seen in your package.json), then try deleting your node_modules folder, and rerunning npm install.
I believe that this is caused by running Angular 6 with an earlier, incompatible version of typescript (<2.7), because it looks like the ability used by the container.d.ts file (referenced in your error) to use Constant-Named Properties was added in Typescript 2.7. Of course, if it were that simple then ng serve would tell you about the Typescript incompatibility, so I assume that I'm either wrong, or that your environment is playing tricks on you.
See here for a related question.


text:
Q: Global variable in header file without extern Using global variable in header file we can change value/use variable in another file(same value can access/modify in multiple files), then why extern can be used ? What is difference between global and extern ?
Below is the example that i have tried It doesnt make difference between extern and global variable in c.
Program compile and run successfully without any error.
t.h
int i;

t1.c
#include<stdio.h>
#include "t.h"

int main()
{
        i=10;
        printf("%s i = %d\n",__func__, i);
        t2();
        printf("%s i = %d\n",__func__, i);
        i=200;
        printf("%s i = %d\n",__func__, i);
        t3();
        printf("%s i = %d\n",__func__, i);

return 0;
}

t2.c
#include<stdio.h>
#include "t.h"

void t2()
{
        printf("%s i=%d\n",__func__, i);
        i = 100;
        printf("%s i=%d\n",__func__, i);
}

t3.c
#include<stdio.h>
#include "t.h"

void t3()
{
        printf("%s i=%d\n",__func__, i);
        i = 300;
        printf("%s i=%d\n",__func__, i);
}

Output :- gcc t1.c t2.c t3.c
main i = 10
t2 i=10
t2 i=100
main i = 100
main i = 200
t3 i=200
t3 i=300
main i = 300

A: See C11 6.9.2p2

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition.

So that's what you have: a tentative definition.
Try different variations in file t.h
int i;
int i = 42;
static int i;
static int i = 42;
extern int i;

The description of the various options at gcc documentation may be of help

-fno-common
In C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with the extern keyword, which do not allocate storage.
Unix C compilers have traditionally allocated storage for uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This is the behavior specified by -fcommon, and is the default for GCC on most targets. On the other hand, this behavior is not required by ISO C, and on some targets may carry a speed or code size penalty on variable references.
The -fno-common option specifies that the compiler should instead place uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker so you get a multiple-definition error if the same variable is defined in more than one compilation unit. Compiling with -fno-common is useful on targets for which it provides better performance, or if you wish to verify that the program will work on other systems that always treat uninitialized variable definitions this way.


text:
Q: Unit Test case for Generic HttpGet methods How can I write test cases for Generic Http methods. My methods are below.
    public async Task<T> HttpGetAsync<T>(string urlSuffix)
    {
        var url = Common.FormatUrl(urlSuffix, _instanceUrl, _apiVersion);
        return await HttpGetAsync<T>(url);
    }

    public async Task<T> HttpGetAsync<T>(Uri uri)
    {
        try
        {
            var response = await HttpGetAsync(uri);
            var jToken = JToken.Parse(response);
            if (jToken.Type == JTokenType.Array)
            {
                var jArray = JArray.Parse(response);
                return JsonConvert.DeserializeObject<T>(jArray.ToString());
            }
            // else
            try
            {
                var jObject = JObject.Parse(response);
                return JsonConvert.DeserializeObject<T>(jObject.ToString());
            }
            catch
            {
                return JsonConvert.DeserializeObject<T>(response);
            }
        }
        catch (BaseHttpClientException e)
        {
            throw ParseForceException(e.Message);
        }
    }

 protected async Task<string> HttpGetAsync(Uri uri)
{
  var responseMessage = await _httpClient.GetAsync(uri).ConfigureAwait(false);
  if (responseMessage.StatusCode == HttpStatusCode.NoContent)
  {
    return string.Empty;
  }

  var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
  if (responseMessage.IsSuccessStatusCode)
  {
    return response;
  }

  throw new BaseHttpClientException(response, responseMessage.StatusCode);
}


text:
Q: Apache. View only access on a directory Within apache can I restrict users to listing the contents of a directory or is it true to say that once a user has been allowed access there is nothing to restrict them from downloading the content?

A: <Directory "c:/[your path]">

Order Allow,Deny
Allow from all

#Options Indexes

    <LimitExcept ALL>
         require user [your user]
    </LimitExcept>
</Directory>

Without the Option Indexes in the file *.conf, the user can't listing the content of the directory. They steal can access to a ressource of the file.
I think it was what you asking for!


text:
Q: DocuSign OAuth Flow + Connect Some more background information since my original post may not have been as clear as I had hoped (note this is all in the sandbox): my DocuSign account is connected to two different accounts, one for local dev and another created for staging / prod that I was added to. We have integrator keys and OAuth configs for both accounts. We also have configured Connect webhooks for both, the end-point for my account tunnels to my localhost through ngrok and the ones for the web app points to the same end-point, but with prod / staging hostname.
When testing locally I could login through OAuth with my test account and then our web app would send a document out for signature using my test account's access token. Once signature was complete the connect end-point to tunnel to my localhost would get called and the web app would then fetch the signed document using the user who sent it's access token. It seemed to all work properly, but when retesting in the staging env I noticed that although the integrator key had switched it was actually picking up on the Connect settings for the user I logged in as rather than the Connect settings of the account for the integrator key (I could see the Connect end-point getting hit in my local logs). When initiating the OAuth flow with another separate test user with no Connect settings at all Connect didn't seem to fire at all (no trace in the logs / fails).
What it really boils down to is: When a document's signatures are all in and it is considered complete, does it check the Connect settings for the account of the integrator key or the account which was used to sign in via the OAuth flow? I had assumed it would be the account of the integrator key, but my experience seems to be telling me otherwise.
I hope this clears up my issue / confusion for people who may be reading.
original text from initial post below:

OAuth works great for sending documents out for signature and voiding, but when signing is complete the Connect settings seems to be picking up for the settings of the user who initiated the flow rather than the settings for the app. Wondering if this is the intended behaviour or if i'm missing something.
Since we can't expect our users to enter our Connect end-point in their DocuSign settings as part of on-boarding them (nor would we want to since it would mean all documents including ones not sent from our app would get posted to it) I'm wondering what the best practice is here. I realize that we can get the functionality we want if we abandon Connect and switch to a polling strategy using the users stored access keys, but we would prefer to stick with using Connect if possible.
Is anyone else using OAuth + Connect for their DocuSign integration?

A: Integrator keys (client_ids in OAuth-speak) are independent of accounts.
A client_id represents a client of the API. Clients are independent of accounts. A particular piece of Client software (and its client_id) can be used by anyone with access to the client software.
In order to access the API via a client, someone needs to be the authenticating user. That is the person who granted permission (via OAuth) for the client to access the API as that person.
The Connect webhook settings are associated with an account, not with a client_id. I recommend using the API to create/check/modify the connect settings. That way your app ensures that the settings are as they should be.
eventNotification webhook settings are set per envelope.
HTH, please respond in comments if it isn't clear.


text:
Q: How to upgrade Samba on old NAS DNS-323 I have an old D-Link DNS-323 that doesn't have updates anymore.
I found a way to connect to it through Telnet so I can try to update it manually. Then I would compile the latest Samba version, but it requires (at least) Python3. So I have to compile it also. I found a gcc version that shall work on this limited Linux version.
To transfer files to the NAS, I temporarely activated SMB1.0 under Windows 11.
Here are the current steps I did:

*

*Turn on SMB1.0: https://tompai.pro/computers/d-link-dns-323-requires-smb1-protocol-cant-connect-from-windows-10/

*Install fun_plug : https://nas-tweaks.net/371/hdd-installation-of-the-fun_plug-0-7-on-nas-devices/#Steps_for_installing_fun_plug

*Install GCC:

*

*http://dns323.kood.org/howto:crosscompile#pre-compiled_binaries (Not working)

*http://uclibc.org/downloads/binaries/0.9.30.1/mini-native-armv5l.tar.bz2 (Used way)

*Compile Python

*

*First error gotten: "-std=c11" not recognized by gcc
==> I removed this option from Makefile

*Second:

Parser/pegen.c:63: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function 'growable_comment_array_deallocate':
Parser/pegen.c:125: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_get_keyword_or_name_type':
Parser/pegen.c:140: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_resize_tokens_array':
Parser/pegen.c:196: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_PyPegen_is_memoized':
Parser/pegen.c:307: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_PyPegen_get_last_nonnwhitespace_token':
Parser/pegen.c:444: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_PyPegen_soft_keyword_token':
Parser/pegen.c:550: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function '_PyPegen_Parser_Free':
Parser/pegen.c:807: error: 'for' loop initial declaration used outside C99 mode
Parser/pegen.c: In function 'reset_parser_state_for_error_pass':
Parser/pegen.c:818: error: 'for' loop initial declaration used outside C99 mode

May someone give me some assistance to be able to use SMB version >= 2.0 so I can deactivate the feature in Windows (and thus being more secure).

A: I've gone through a lot of issues that I won't even sum up here. The solution I opted for was to switch to Debian.
You can see the whole instructions story here.
Here is a copy paste of the instructions:

Warning Read those notes before going any further

⚠ Make sure to have a backup because this procedure will wipe all your data.
⚠ If somehow, you are stuck somewhere, you might find a solution, you might get help, BUT always remember that it could be possible you will have to use the serial method to recover to the original firmware.
⚠ The D-Link DNS-323 is no longer supported by Debian.

Debian
Replacing original firmware

*

*Download https://ftp.nl.debian.org/debian/dists/jessie/main/installer-armel/current/images/orion5x/network-console/d-link/dns-323/netboot.img on your computer.

*Use the web interface of your DNS-323, in the firmware update section, and select the previously downloaded file.

*Proceed with "updating" your firmware. ⚠ Don't turn off / reboot your DNS-323 until it ends.

*Reboot the hardware.

Finding the new IP address and connecting

*

*Get your computer IP address:

*

*Via command line:

*

*Open cmd.

*ipconfig

*Look for the network adapter currently in use (the IP address shall start with 192.168..

*Via GUI:

*

*Open Windows parameters / control panel.

*Reach the network settings.

*View the details of the currently in use adapter.

*Open NMap (You can use the software of your choice that would achieve the same goal).

*In target box, you can enter 192.168.1.0/24 (the IP address of your computer except the last number is replaced with 0).

*In command box, add -p 22 after nmap.

*Click on the scan button.

Scanning 26 hosts [1 port/host]
Discovered open port 22/tcp on 192.168.1.HIDDEN
Discovered open port 22/tcp on 192.168.1.HIDDEN
Discovered open port 22/tcp on 192.168.1.123
Discovered open port 22/tcp on 192.168.1.HIDDEN

All the HIDDEN keywords were in fact numbers, but for privacy, I obfuscate them. I left them here so you can see that you could have multiple devices having the port 22 opened. So, from there, you can discard all known IP addresses. If there is more then one left, you can try to connect vis SSH and if it connects, you found it. Here the IP address 192.168.1.123 would be my device (this is not the real one).

*

*Open Putty or WSL (Windows Subsystem for Linux) that I now prefer over Putty for SSH.

*ssh installer@192.168.1.123
Username: installer
Password: install

Installing the operating system

*

*Go to shell directly with this first SSH connection. I will name it SSH-behind-the-scene (shorten SSH-b ).

*date -s '2020-01-01 11:00:00'

*tail -f /var/log/syslog

*Open another SSH connection. I will name it SSH-installation (shorten SSH-i ).

OK! Now, to discern in what connection I am doing things, I'll prefix the step with its shortname when I change of context.

*

* Choose Expert mode.

*In choosing server step, select Enter manually.

*

*Type archive.debian.org.

*Accept default choices.

*In modules step, select: fdisk, lvm-cfg, md+lvm, partman ext3, partman raid.

* If it is your first boot, then, using fdisk, delete all partitions and ensure GPT on both disks.

* In language step, select your region, BUT do NOT add keyboard layout/locales.

*Follow steps up to partionning and enter it.

*If it is your first boot:

*

*Select Manual.

*Follow the Configure RAID menu. I recommend using RAID-1 as it is more safe for your data, but you are free, it shouldn't change the following steps.

*Reboot NAS and start this section over.

* cat /proc/mdstat
If you get:
The RAID is currently syncing. (This is a paraphrase)

Use while true; do printf "\033\143"; cat /proc/mdstat; echo "CTRL-C to quit"; sleep 10; done until you get the result below then reboot.
If you get following result right away, then continue:
The RAID is active. (This is a paraphrase)

*

* In partionning step, select Guided LVM.

*

*Give the names you want.

*Select both disks.

*Continue up to install base system.

*

*STOP on kernel choice.

* nano /target/usr/sbin/mkinitramfs:

*

*Search for MODULES=most.

*Comment all the "case" lines except auto_add_modules.

* In install base system.

*

*Choose linux-image-orion5x.

*Continue up to Configure package manager.

*

*I chose No to first two choices, security updates only.

*Continue up to Make the system bootable and WAIT.

* . /lib/chroot-setup.sh

*Change to MODULES=loaded in /target/etc/initramfs-tools/conf.d/driver-policy and /target/etc/initramfs-tools/initramfs.conf.

*chroot /target lsmod | cut -f 1 -d\  > /target/etc/initramfs-tools/modules

*Ensure /target/etc/initramfs-tools/modules first line is not "Module", if so delete it.

*nano /target/usr/sbin/mkinitramfs:

*

*Search for MODULES=most.

*Comment all the "case" lines including auto_add_modules

*chroot_cleanup

I am confident that the above modification could replace previous modification made when it was the install base system step. If you want to try/test it.

*

* Proceed with the other installation steps.

* shutdown -r now. (If needed)

After reboot...

*

*ssh USERNAME@192.168.1.123
Making a complete NAS

Note: I am not 100% ensure if there is no useless sudo.

I decided to create a main folder where all my shares would be and to begin with I have:

*

*mkdir -p /share/data

*chmod 777 /share/data

*mkdir -p /share/scripts

*chmod 777 /share/scripts

Here I opened file permissions for those to full, but you can lower it or do what ever you want.

Sudo

*

*su

*apt install sudo

*usermod -aG sudo USERNAME. Where USERNAME is the username you used during Debian installation section.

*Restart SSH session.

Postfix

*

*sudo apt install postfix

*

*Choose Internet with smarthost.

Fan

*

*sudo apt-get install lm-sensors

*sudo sensors-detect

*

*YES to all

*sudo /etc/init.d/kmod start

*sudo apt-get install fancontrol

*sudo pwmconfig

*sudo /etc/init.d/fancontrol start

monitor-fans.sh execution modes:

*

*No param: Tells you if the fan works.

*--install: Install monitoring each 5 minutes.

*--uninstall: Uninstall monitoring.

*

*wget -O /share/scripts/monitor-fans.sh https://raw.githubusercontent.com/djon2003/DNS-323/2.3-Add-ons/files/monitor-fans.sh

*sudo /share/scripts/monitor-fans.sh --install
NTP

*

*sudo apt install ntp
New locales (for UTF-8)

*

*sudo dpkg-reconfigure locales
RAID monitoring

*

*sudo nano /etc/mdadm/mdadm.conf :

*

*Add MAILADDR my-email@domain.com. Where my-email@domain.com has to be replaced by your email.

*To test email:

*

*Kill any mdadm process.

*sudo mdadm --monitor --scan --test

*To test failure:

*

*Ensure the following command is running or run it: mdadm --monitor --scan &.

*mdadm --manage --set-faulty /dev/md0 /dev/sdb1

*Wait to receive the email.

*mdadm /dev/md0 -r /dev/sdb1

*mdadm /dev/md0 -a /dev/sdb1
Samba

*

*sudo apt-get install samba

*sudo bash -c 'echo "include = /etc/samba/smb.share.conf2" >> /etc/samba/smb.conf'

*sudo wget -O /etc/samba/smb.share.conf https://raw.githubusercontent.com/djon2003/DNS-323/2.3-Add-ons/files/smb.share.conf

*sudo systemctl restart smbd
USB port

*

*Install exFAT support: sudo apt install exfat-fuse exfat-utils.

*Install NTFS support: sudo apt install ntfs-3g.

*Printer: I will let this exercise to the reader. As this one I've been able to do  it, but that's true for my model. Maybe in the future.

Automount / Autoshare USB disks
Compile & Install USBMount

*

*sudo apt-get install debhelper build-essential

*mkdir /share/temp-install

*cd /share/temp-install

*wget https://github.com/rbrito/usbmount/archive/refs/heads/master.zip

*unzip master.zip

*cd usbmount-master

*sudo dpkg-buildpackage -us -uc -b

*dpkg -i ../usbmount_0.0.24_all.deb

*cd /

*rm -rf /share/temp-install
Configuration & script to ensure share alive

*

*sudo nano /etc/usbmount/usbmount.conf:

*

*Add to FILESYSTEMS exfat ntfs fuseblk ntfs-3g.

*Replace MOUNTOPTIONS value by uid=1000,gid=1000,nodev.

*sudo wget -O /etc/usbmount/mount.d/01_create_samba_share https://github.com/djon2003/DNS-323/raw/2.3-Add-ons/files/01_create_samba_share

*sudo wget -O /etc/usbmount/umount.d/01_remove_samba_share https://github.com/djon2003/DNS-323/raw/2.3-Add-ons/files/01_remove_samba_share

*sudo mkdir /etc/samba/smb.d/

*wget -O /share/scripts/clear-phantom-shares.sh https://github.com/djon2003/DNS-323/raw/2.3-Add-ons/files/clear-phantom-shares.sh

*sudo /share/scripts/clear-phantom-shares.sh --install
Interesting packages

*

*sudo apt-get install usbutils: Tools for the USB port.

*sudo apt install lshw

*

*lshw -C network : To show  network adapter.

*sudo apt-get install eject

*

*eject /dev/sdc : To disconnect/umount USB drive

*sudo apt-get install udisks2 : Utilitary for USB. i.e. power-off. In my case, using udisksctl power-off -b /dev/sdc, made my USB HDD to be completely off. USB reconnection didn't work. I had to unplug the power cable and replug all to have the disk detected again. But, could be useful.

References
Debian

*

*https://md.ekstrandom.net/resources/dns323/

*https://wiki.debian.org/InstallingDebianOn/D-Link/DNS-323

*http://www.cyrius.com/debian/orion/d-link/dns-323/

*http://www.cyrius.com/debian/orion/d-link/dns-323/install/

*https://www.debian.org/releases/jessie/

*https://www.linuxquestions.org/questions/debian-26/how-do-i-create-an-initrd-img-file-597883/
Recovery

*

*http://www.cyrius.com/debian/orion/d-link/dns-323/recovery/

*http://dns323.kood.org/hardware%3Aserial

*https://www.ionos.com/help/server-cloud-infrastructure/dedicated-server-for-servers-purchased-before-102818/rescue-and-recovery/software-raid-status-monitoring-linux/
RAID

*

*https://tldp.org/HOWTO/Software-RAID-HOWTO-6.html

*https://serverfault.com/questions/495392/remove-faulty-state-in-raid-1
Samba

*

*https://tompai.pro/computers/d-link-dns-323-requires-smb1-protocol-cant-connect-from-windows-10/

*https://www.samba.org/samba/docs/current/man-html/smb.conf.5.html

*https://www.samba.org/samba/download/

*https://wiki.samba.org/index.php/Build_Samba_from_Source

*https://www.samba.org/samba/history/

*https://wiki.samba.org/index.php?title=Package_Dependencies_Required_to_Build_Samba&oldid=10463#Python

*https://askubuntu.com/questions/917565/checking-smb-version

*https://askubuntu.com/questions/79078/how-to-restart-samba-server

*https://linuxconfig.org/how-to-set-up-a-samba-server-on-debian-10-buster
Add-ons

*

*https://www.cyberciti.biz/faq/how-to-find-fan-speed-in-linux-for-cpu-and-gpu/

*https://unix.stackexchange.com/questions/134797/how-to-automatically-mount-an-usb-device-on-plugin-time-on-an-already-running-sy

*https://github.com/rbrito/usbmount
Others

*

*https://nas-tweaks.net/371/hdd-installation-of-the-fun_plug-0-7-on-nas-devices/#Steps_for_installing_fun_plug

*http://dns323.kood.org/howto:crosscompile#pre-compiled_binaries

*https://devguide.python.org/getting-started/setup-building/
Credits

*

*Software terminal icons created by Freepik - Flaticon

*People on irc://irc.debian.org/#debian-arm

*People on StackOverFlow or their related sites.


text:
Q: Problem with quarkus kafka smallrye consumer multithreading I set this properties but, quarkus doesn't work correctly.

*

*smallrye

*kafka have 3 partitions

mp:
  messaging:
    incoming:
      event:
        connector: smallrye-kafka
        auto:
          offset:
            reset: earliest
        topic: MY_TOPIC
        group:
          id: my-group
        partitions: 3

I see that I have 3 different consumer ids, but the messages are processed sequentially.
I try with all 2.X quarkus version
Anyone can Help me?