text:
Q: Why static object of non-static class cannot be created inside a method? I can see that static object of non-static class cannot be created inside a method?
Code:
  public class Rent {

      public void abc() {
          System.out.println("Non static method");
      }
      public static void def() {
          System.out.println("this is static method");
      }
  }

  public class SampleJava {

      public static void main(String[] args) {
          Rent r1 = new Rent();
          public static Rent r2; //not allowed in static method
      }

      public static Rent r3; //allowed outside method

      public void def() {
          Rent r4 = new Rent();
          public static Rent r5; //not allowed in non-static method either
      }
  }

A: There are few points you have to consider:

*

*Static Data is similar to a Static Method. It has nothing to do with the instance. A value that is declared static has no associated instance. It exists for every instance, and is only declared in a single place in memory. If it ever gets changed, it will change for every instance of that class.

*The access modifiers you have used are only allowed for class level and not method level.
In your example:
public static void main(String[] args) {
  Rent r1 = new Rent();
  public static Rent r2; //Will give compile time error.
}

*Considering the purpose of "Static", if you are declaring the static object inside the method then its scope will be bind to that particular method only.

Usually the static objects are used to maintain the state.

For e.g. your database connection logic may have a singleton class and the object of this class should keep your state of database connection.
These objects needs to be and must be at class level.

A: The errors you are getting have nothing to do static/instance access. They are just compile time errors because of invalid Java syntax.
You cannot use field modifiers like public and static for declarations of local variables inside a method (be it a static or an instance method).
Just remove the unnecessary modifiers:
  public static void main(String[] args) {
      Rent r1 = new Rent();
      Rent r2;
  }

  public static Rent r3;

  public void def() {
      Rent r4 = new Rent();
      Rent r5;
  }

A: First of all you are not allowed to declare variables with access modifiers(public, private, protected) within a method. You are also not supposed to declare variables as static within a method.
Those variables you declared outside the methods are members of a class.
There are 2 types of variables:

*

*Instance variables (non-static members)

*Class variables (static members)

I can see that static object of non-static class cannot be created inside a method?

static means it belongs to the class. It exist even before you instantiate the object. That is why you could invoke a static method through the class directly.
So what are static members?

*

*static members are shared by all objects from the same class.

*it exist even before you instantiate (create) an object.

*it belongs to the class, and not any individual object.

Example:
class Pond
{
    static double waterTemp = 17.5;  //Every Pond object shares the same value
    int numFishes;                   //Belongs to each individual Pond object
}

How to access static members:
System.out.println(Pond.waterTemp); //Preferred
System.out.println(Pond.numFished); //Not allowed

//OR

Pond pond = new Pond();
System.out.println(pond.waterTemp); //Not necessary, but allowed
System.out.println(pond.numFished); //The only way to get numFishes

A: A non-static method is associated with an instance and hence is required that an instance be created before it can be accessed. However, a static method is related to class and not hence it should be available for use even without an instance. These constraints cause the static method to not be created inside an non-static method.


text:
Q: Pushout of an injective map is injective This is an exercise from Rotman , Introduction to homological algebra.
Given a pushout diagram in $R$-Mod
$$\begin{array}
AA & \stackrel{g}{\longrightarrow} & C \\
\downarrow{f} & & \downarrow{\beta} \\
B & \stackrel{\alpha}{\longrightarrow} & D
\end{array}
$$
prove that $g$ injective implies $\alpha$ injective, and that $g$ surjective implies $\alpha$ surjective.
I have problems with the injective part, how to solve it ?

A: So I applied the construction of pushout in $R$-Mod: $$D \cong (B \oplus C)/S$$ where $S$ is the submodule generated by $$\lbrace (f(a), -g(a) ) | \ a \in A \rbrace$$
Thus if $\alpha(b) = 0 $ we have that $$\alpha(b) = (b,0) \in S \Rightarrow \exists a \in A \ \text{s.t} \ \ (b,0) = (f(a) , -g(a))$$
But this implies $a= 0$ due to injectivity of $g$ and then $b= 0$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using different scopes for same binding I have this binding in my NinjectControllerFactory:
    private void AddBindings()
    {
        ninjectKernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
    }

And it works well for request to controllers, only one unit of work is instantiated.
But when I inject UnitOfWork to my SignalR Hub class the problem is that all method calls in SignalR are in the same request scope, and same instance of UnitOfWork is used all the time while user is connected.
So, I want to use something like: ninjectKernel.Bind<IUnitOfWork>().To<UnitOfWork>().InScope(ctx => MyHubClass); so it gets disposed every time.
But can I somehow use this binding only for injection to HubClass, and the first one for all other requests?

A: Ninject has a extension method called:
.WhenInjectedInto(Type type)
Where you can set which object to inject when injecting in the specific type.
https://github.com/ninject/Ninject/wiki/Contextual-Binding
So, then you could do
ninjectKernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
ninjectKernel.Bind<IUnitOfWork>().To<UnitOfWork>().WhenInjectedInto<MyHubClass>().InScope(ctx => ...);

Hope that helps.
Sorry, if I mistyped something I haven't got my VS open


text:
Q: The incompatibility between Cloudflare and the reverse DNS I'm already activated Cloudflare for my website and to apply that I had to replace my domain default nameservers with Cloudflare nameservers. Now my website has to send emails to the mail servers, but I have a problem with that, especially with the 3 major mail servers.
Gmail and Hotmail receive my website emails in Spam/Junk folder not in inbox, and Yahoo mail doesn't receive messages from my website at all. So in order to solve this issue I was recommended to set a reverse DNS for my website.
Now to do that I had to set a PTR records in my domain settings so reverse DNS lookup of my hosting IP should lead to my domain, but because my domain provider ( name.com ) doesn't offer that, I was told to solve this issue through my hosting provider ( OVH ). But my hosting provider told me I have to solve this issue with Cloudflare support as long as I use Cloudflare servers to protect my website. In Cloudflare support section I read that they don't offer PTR records too and such issue should be solved by the hosting provider, so I'm really stuck in a very narrow place now!
The reverse DNS lookup ( my hosting IP ) leads to my domain, but DNS lookup ( my domain ) leads to Cloudflare IP not to my hosting IP.
If I removed Cloudflare namerservers and bring back the default nameservers in my domain account the problem will be solved, but I need to keep Cloudflare in my website, and in the same time I need my website outcoming emails be accepted by all email servers.
Can you help me to solve this issue.

A: The PTR record will need to be set at OVH, however, before being able to do that, you will need to create an A record at CloudFlare for the servers hostname and set that record to not pass through CloudFlare. Say, for example, if your server name is server.domain.com, do the following:

*

*In CloudFlare, create an A record for server.domain.com with the IP of your server. Make sure it does not pass through CloudFlare.

*Ask OVH to setup Reverse DNS for your IP to server.domain.com.

*Make sure the MTA on your server uses server.domain.com in the HELLO line. Usually it sets it automatically from the hostname.

A: Consider not using cloudflare for your email server. Simple like that. Website and email on separate IP addresses and voila. I have the PTR records set by my internet provider and email is not routed through cloudflare.


text:
Q: Hiding certain rows of a table using JS, if I have a table set up as such:

<col class="quantity"></col>
<col class="price"></col>
<col class="total"></col>

Quantity
Price
Total

50,000
10.25
512,500

1,250
8.10
101,125

Using JavaScript, how can I hide rows based on the quantity of one or more cells? Like if (the price is less than 5), or (the price is less than 10 and quantity is greater than 1,000), have the whole row skipped over.

A: I'm only answering this because the horrendous jQuery answer needs to have a substitute.
Place the following in a


text:
Q: React on global hotkey in a Java program on Windows/Linux/Mac? A Java6 application sits in the system tray. It needs to be activated using a hotkey (e.g. Super-G or Ctrl-Shift-L etc) and do something (e.g. showing an input box).
How do I do that on:

*

*Windows (XP or Vista)

*OS/X

*Linux (Gnome or KDE)

A: For Linux (X11) there is JXGrabKey: http://sourceforge.net/projects/jxgrabkey/
There is also a tutorial for grabbing a global hotkey on Linux: http://ubuntuforums.org/showthread.php?t=864566
I didn't though find a solution for OS X yet.
To build something for all 3 platforms I'd suggest stripping down JIntellitype (it's Apache license) to it's global hotkey functionality and extending it with the OS X and X11 functionality...

A: It seems that this is not doable in a cross-platform fashion without using the native interfaces.
On Windows, you can use the free JIntellitype library.

A: If anyone wants to do the OSX or Linux versions of the JNI part of Jintellitype I would be more than happy to add those to the JIntellitype library.
Melloware
http://www.melloware.com

A: I've compiled a library for global hotkeys in java using JNA. It currently supports Windows, Linux and Mac OSX. It also supports media keys on windows and linux.
if anyone is interested, try https://github.com/tulskiy/jkeymaster
I would appreciate any feedback.
Thank you.

A: I found this solution to work just great on windows. It does not require you to install any software like JIntelliType. Note that this is 32 bit dll and you can recompile for 64-bit JVM is do desire. All credits to original author of the blog.

A: I've written a Java library for global key/mouse events here. This works for Windows, Linux X11, and OSX.
https://github.com/repeats/SimpleNativeHooks


text:
Q: Rate limiting Kedro API requests I have a few datasets from the government dataset that I'm using on my ML model, the problem is, their server is not that great to put it nicely. Whenever I run my pipeline, when I pull from their API all at once, their server goes down for a few minutes.
This is how their data is represented on our catalog.yml:
external-safra-cana:
  type: api.APIDataSet
  url: https://apisidra.ibge.gov.br/values/t/6588/p/all/v/allxp/c48/39456/n3/all

external-safra-algodao:
  type: api.APIDataSet
  url: https://apisidra.ibge.gov.br/values/t/6588/p/all/v/allxp/c48/39429/n3/all

external-safra-arroz:
  type: api.APIDataSet
  url: https://apisidra.ibge.gov.br/values/t/6588/p/all/v/allxp/c48/39432/n3/all

external-safra-milho1:
  type: api.APIDataSet
  url: https://apisidra.ibge.gov.br/values/t/6588/p/all/v/allxp/c48/39441/n3/all

external-safra-milho2:
  type: api.APIDataSet
  url: https://apisidra.ibge.gov.br/values/t/6588/p/all/v/allxp/c48/39442/n3/all

What I want to do is, if the data fails to download, I want to sleep for a few seconds and retry, but I could not find anything like that on the documentation, is there a way to get this behavior from the APIDataSet?

A: I would consider subclassing the APIDataSet and building in a caching mechanism - you could say pickle responses and build some sort of 'expiry' mechanism where you:

*

*If pickle doesn't exist, call API and save response as pickle

*If pickle exists and within 'fresh' window, read from pickle

*If pickle exists and outside 'fresh' window, call API and create new pickle

This isn't something that's come up a lot with users so we haven't built any native way of doing it.


text:
Q: Caused by: java.lang.IllegalArgumentException: Can not set int field com.example.demo.pojo.PurchaseOrder.orderNo to java.lang.Integer I am trying to persist an entity using springboot data JPA. Faced this issue stating cannot set int field to java.lang.Integer.Below are my classes.
PurchaseOrder.java
    @Entity
@Table(name = "PurchaseOrderTable")
@Component
public class PurchaseOrder {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int orderNo;
    @Column
    private String billNo;
    @Column
    private String purchageShop;
    @Column
    private String gstNo;
    @OneToMany(targetEntity = ProductPurchase.class, cascade = CascadeType.ALL)
    private List<ProductPurchase> products;
    @Column
    private int totalPrice;
    @Column
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime purchaseDate; ...

ProductPurchase.java
@Entity
@Component
@Table(name = "ProductPurchaseTable")
public class ProductPurchase {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column
    private int quantityPurchased;
    @ManyToOne(targetEntity = PurchaseOrder.class, cascade=CascadeType.ALL)
    private int orderNo;
    @Column
    private float totalProductPrice;
    @Column
    private String productName;
    @Column
    private String productBrand;
    @Column
    private String productSize;
    @Column
    private String unit;
    @Column
    private String description;
    @Column
    private int unitPrice;

Reository:
@Repository
public interface PurchaseRepository extends JpaRepository<PurchaseOrder, Integer> {

I faced this exception while persisting the entity.
Note: I am using Springboot with JPA and database is in memory H2 db.
Please help me to resolve this issue.

A: The id needs to be an Integer:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

You also need to make the same change in ProductPurchase
@ManyToOne(targetEntity = PurchaseOrder.class, cascade=CascadeType.ALL)
private Integer orderNo;

or even better:
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="orderNo")
private PurchaseOrder purchaseOrder;

I would also suggest to change the id of ProductPurchase to Long.
In general, I would avoid having a primitive type as an identifier because then you cannot check if the id is null for newly created entities, you will have to check if it's bigger than 0.


text:
Q: iOS: Resizing popover dynamically I have an UIViewController that is presented as a popover. I set preferredContentSize in viewDidLoad and it works well.
I would like to add elements to the popover dynamically and i am looking for a way to resize the whole popover.
I tried resetting preferredContentSize but it does not seem to have any effect after at this point.
Is there a way to resize the popover dynamically?

I looked at the solutions suggested in the comments, but they require the use of contentSizeForViewInPopover, which is deprecated since ios 7


text:
Q: Using hitTest instead of mouseOver / mouseOut Almost all of the Flex components have mouseOver/mouseOut or rollOver/rollOut events. Requires that these events called not the mouse cursor, but on the other element, such as Image or Bitmap.
For example, there is a Colomn Chart and image animations above it and I need to get the data (colomn value or index) when the image is over the column. If it were a component, then I would use hitTest. But what to do if it is chart?

A: Can't you tell the image/bitmap to not be mouseEnabled?

A: i can't understand your question properly, eventhough i m trying this...
if you add mouselisteners on the chart and whenever the event is dispatch check..
position.x = event.currentTarget.mouseX;
position.y = event.currentTarget.mouseY;

then you can try with hitTest.
or
if(obj.hitTestPoint(position.x,position.y)){

}

this might be work....


text:
Q: Send mail without user interactions with Intent in android I want to send a mail when user clicks a button and also i should not get any interaction after that and mail should be sent automatically using email client in the mobile.
Please help me to find the solution.
Thanks in advance.

A: I agree with @TGMClains if u want that there is no user interaction with the mail client in the phone then you need to create your own email client ...check out this following post.
Sending Email in Android using JavaMail API without using the default/built-in app
Hope this solves your problem

A: Simply it is not possible to send the email through email client like Gmail without user interaction.
Instead of Java Mail API, I recommend you to make any Web API in PHP and code there to send the mail and call this Web API in your Android code.

A: In your onClick() put this :
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:to@gmail.com"));


text:
Q: Can I sysprep a bootable VHD without using any virtualization technology? I booted from a VHD on my laptop and hoped to sysprep this image, but it didn't let me do it. I got a fatal error during the process. I used the following command: sysprep /generalize /shutdown. My question is it possible at all to sysprep a VHD without any HyperV or virtual PC technology?

A: Sysprep doesn't care about the underlying technology. It will work on physical or virtual hardware.  The issue that you've run into is probably caused by something else.  Can you provide more details on what errors you have?

A: I had this problem as well. After seeing http://social.technet.microsoft.com/Forums/en/w7itproinstall/thread/8f5002e1-95b4-47bf-b031-4b72b3eb388a I killed the wmpnetwk.exe process and sysprep worked fine


text:
Q: преобразование base64 в файл С клиента на сервер приходит JSON формы, в одном из полей которой хранится картинка в виде base64. Как эту картинку средствами PHP 5 сохранить на сервер в файл по нужному пути?
Сделал вот так:
$base64_decode  = base64_decode ($response["image_opt"]);
$dirSave = DOCROOT.'uploads/'. uniqid(). '.jpg';
file_put_contents($dirSave, $base64_decode);

Файл на диск сохраняется, но не открывается через просмоторщик Windows.

A: Попробуйте так:
function base64ToFile($data, $path) {
    $source = fopen($data, 'r');
    $destination = fopen($path, 'w');

    stream_copy_to_stream($source, $destination);
    fclose($source);
    fclose($destination);
}


text:
Q: Updated my system, now VMWare can't update its kernel modules After updating my system (with whatever was in the 18.04 repositories in recent weeks), VMWare can't update it's kernel modules. I hit Install on the VMWare Kernel Module Updater and it says it's trying to do "vmmon" and "vmnet". But it fails, saying "Unable to install all modules. See log /tmp/vmware-myhostname/vmware-1711.log for details. (Exit code 1)"
Here are the contents of this file: https://pastebin.com/hN6F6895

A: I downloaded and installed the latest VMWare Player from VMWare and now everything works. I had been running 15.5.1, now I am on 15.5.6. You get a .bundle file - I just chmod +x reallylongfilename it and sudo ./reallylongfilename and Bob's your uncle.
If updating VMWare Player isn't an option, you might wish to look at this thread: https://communities.vmware.com/thread/623768
Somebody is running a repo that has patches needed to build host modules against recent kernels: https://github.com/mkubecek/vmware-host-modules (this is mentioned a few times in that thread).
But the simplest thing is just to go to the latest VMWare Player and see if that works - it did for me.


text:
Q: Adding items to a list in XAML C# Well I have a class Employee. In this class I have a property
public List<Project> Projects { get; set; }

The project class looks like this:
   public class Project
  {
    public int Id { get; set; }
    public string Name { get; set; }
  }

Now I want to add to an employee a list with projects in the xaml:
 <models:Employee Firstname="Jane" Lastname="Doe">
                <models:Employee.Projects>
                    <models:Project Id="1" Name="Abc"></models:Project>
                </models:Employee.Projects>
            </models:Employee>

Now the models:Employee.Project gets underlined and if I hover over I get the error:
Value cannot be null. (Parameter 'key')


text:
Q: Update Location on Interval This is the current code I have to show the last known good location as a marker on a Google Map. All is functional, but I'd like to update the location on an interval (say 1 minute or 5 minutes.) What is the best way to implement this given the current code I'm using?
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class Parking extends Activity implements OnClickListener {

    private GoogleMap map;

    Button b;

    public static final String LATITUDE = "latitude";
    public static final String LONGITUDE = "longitude";

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

        b = (Button)findViewById(R.id.button1);
        b.setOnClickListener(this);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        if (map!=null)
        {

        //Set Map Type
        map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

        //Enable MyLocation Layer of Google Map
        map.setMyLocationEnabled(true);

        //Get LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        //Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        //Get the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        //Get Current Location
        Location myLocation = locationManager.getLastKnownLocation(provider);

        //Get Lat/Long of the current location
        double latitude = myLocation.getLatitude();
        double longitude = myLocation.getLongitude();

        //Create a latLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        //Show the current location in Google Map
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        //Zoom to location
        map.animateCamera(CameraUpdateFactory.zoomTo(16));

        //Add marker
        map.addMarker(new MarkerOptions()
            .position(new LatLng(latitude, longitude))
            .title("You Are Here")
        );

        }//end if map !null
    }

A: You can use the requestLocationUpdates methods of the LocationManager class - http://developer.android.com/reference/android/location/LocationManager.html
You can specify the time interval in millis and also the minimum distance change in meters.
My suggestion is to switch to the newest Location API as explained here: https://developer.android.com/google/play-services/location.html

A: With the new introduced Fused Location Providers from Google it is much easier to get the location or to get periodic updates ! See this link which might be very helpful
https://developer.android.com/training/location/receive-location-updates.html
All you need is too import google-play services to you project,
and also you may use a background service to get periodic updates.
public class UpdateLocation extends Service
        implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener,
            LocationListener {

private static final long UPDATE_INTERVAL = 300000;
private static final int FASTEST_INTERVAL = 60000;
private LocationRequest lr;
private LocationClient lc;
private Location l;

@Override
public void onCreate() {
    super.onCreate();
    lr = LocationRequest.create();
    lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    lr.setInterval(UPDATE_INTERVAL);
    lr.setFastestInterval(FASTEST_INTERVAL);
    lc = new LocationClient(this, this, this);
}

@Override
public void onStart(Intent intent, int startId) {
    lc.connect();

}

@Override
public void onLocationChanged(Location l) {
 //do updates on Location change.
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {

}

@Override
public void onConnected(Bundle arg0) {
    Log.d("AutoTracker : Test", "Location Client Connected");
    if (updates) {
        lc.requestLocationUpdates(lr, this);
    }

}

@Override
public void onDestroy() {
    if (lc.isConnected()) {
        lc.removeLocationUpdates(this);
    }
    lc.disconnect();
}

@Override
public void onDisconnected() {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}


text:
Q: Unexpected getting cloud_firestore/permission-denied in production sometimes My Firestore rule:
match /app/info {
  allow read;
}

My code:
FirebaseFirestore.instance
        .collection('app')
        .doc('info')
        .snapshots()
        .listen(
        (event) {
          final _minVersion = event.data()?['min_version'];
          if (_minVersion is! String) return;
          shouldUpdateApp(Version.parse(_minVersion), context.appLoc);
        },
        onError: (Object error, StackTrace? stackTrace) {
          FirebaseCrashlytics.instance.recordError(
            error,
            stackTrace,
            reason: 'app info onError',
          );
        },
      )

And is working perfectly in development.
However, sometimes in production I get errors reported to Firebase Crashlytics.

Non-fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError
[cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.. Error thrown app info onError.

Update 18 May 2022:
This only happens when the device is 100% running in background.


text:
Q: How can I call a function after an event is resolved in another client-side module? I'm a beginner. I'm creating an app that relies on an in-browser editor, in this case monaco editor.
The editor has this event which occurs after an editor is created:
monaco.editor.onDidCreateModel(()=>{
    initBoard();
})

Within, I have called a function initBoard() which inits some critical actions in my main file. This way however I have some circular imports, and I'm importing from main which I have now found to be bad coding practices.
Instead I want some other way of having the effect of calling initBoard() without having to import from main.
What is typically the best pattern for getting a function in main to call from a module?


text:
Q: Dispalying a vcf file in a textview using android I'm trying to get the content of a .vcf file and put it inside a textview, I just started developing so please be specific.
I'm also trying to use ez-vcard but I can't seem to manage.


text:
Q: Django REST Framework -- How to resolve ForeignKey to Actual Value, not index? I have a model such as:
class Job(models.Model):
    build = models.ForeignKey(Build, on_delete=models.PROTECT)
    name = models.CharField(blank=True, null=True)

and a view:
class JobViewSet(viewsets.ModelViewSet):
    queryset = Job.objects.all()
    serializer_class = JobSerializer

and a serializer:
class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job

The only issue is when I access the API endpoint, I receive data, but the build property from Job model is the actually integer of the foreign key. I want the actual value from that key (which is also a model in my Django rest framework.
I have search a lot and I found some promising articles, but was not getting correct results when I tried various things. I am still new to Django...Can any of you help?

A: First create a serializer for Build like:
class BuildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Build

Next in JobSerializer do like:
class JobSerializer(serializers.ModelSerializer):
    build = BuildSerializer()
    class Meta:
        model = Job
        fields = ('name','build')

A: Use a depth attribute.
class BuildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Build
        depth = 1

A: Use a depth attribute when you want to get all the attributes of a member field in your JobSerializer.
Example, all the fields of the Build Model.If you want to fetch just specific fields,
Like, all fields of a user model except the password field must specify a serializer for the foreign key of the user.


text:
Q: git clone throw an error : Could not resolve hostname Name or service not known fatal: Could not read from remote repository when I git clone form a remote repository , g
I try all ways in google.But it still has the same error.

A: Make sure you have set up necessary proxy settings.
This is commonly needed when you need to access git from your employers network.
in the .gitconfig file (for me located in the user folder) you can add proxy settings.
[http]
proxy = http://username:password@proxyserver:port

Remember, special characters in your username or password need to be url encoded (% notation, see http://www.w3schools.com/tags/ref_urlencode.asp)
You can also set it though the command line with the following command
git config --global http.proxy http://username:password@proxyserver:port

Replace username, password, proxyserver and port by their actual values.
Also make sure you have your ssh keys setup.
Github explains well how to do that: https://help.github.com/articles/generating-an-ssh-key/


text:
Q: Threads increase abnormally in linux service I have a service that runs in linux under SystemD but gets compiled and debugged in VS22 under Windows.
The service is mainly a proxy to a MariaDB10 database shaped as a BackgroundWorker serving clients via SignalR.
If I run it in relase mode on Windows, the number of logical threads remains in a reasonable value (20-25 approx). See pic below.

Under linux, after few minutes (i cannot give you more insight unfortuantely... i still have to figure out what could be changing) the number of threads start increasing constantly every second.
see pic here arriving already to more than 100 and still counting:

Reading current logical threads increasing / thread stack is leaking i got confirmed that the CLR is allowing new threads if the others are not completing, but there is currently no change in the code when moving from Windows to Linux.
This is the HostBuilder with the call to SystemD
 public static IHostBuilder CreateWebHostBuilder(string[] args)
        {
            string curDir = MondayConfiguration.DefineCurrentDir();
            IConfigurationRoot config = new ConfigurationBuilder()

                // .SetBasePath(Directory.GetCurrentDirectory())
                .SetBasePath(curDir)
                .AddJsonFile("servicelocationoptions.json", optional: false, reloadOnChange: true)
#if DEBUG
                   .AddJsonFile("appSettings.Debug.json")

#else
                   .AddJsonFile("appSettings.json")
#endif
                   .Build();
            return Host.CreateDefaultBuilder(args)
                .UseContentRoot(curDir)
                .ConfigureAppConfiguration((_, configuration) =>
                {
                    configuration
                    .AddIniFile("appSettings.ini", optional: true, reloadOnChange: true)
#if DEBUG
                   .AddJsonFile("appSettings.Debug.json")

#else
                   .AddJsonFile("appSettings.json")
#endif
                    .AddJsonFile("servicelocationoptions.json", optional: false, reloadOnChange: true);
                })

                .UseSerilog((_, services, configuration) => configuration
                    .ReadFrom.Configuration(config, sectionName: "AppLog")// (context.Configuration)
                    .ReadFrom.Services(services)
                    .Enrich.FromLogContext()
                    .WriteTo.Console())

                // .UseSerilog(MondayConfiguration.Logger)
                .ConfigureServices((hostContext, services) =>
                {
                    services
                    .Configure<ServiceLocationOptions>(hostContext.Configuration.GetSection(key: nameof(ServiceLocationOptions)))
                    .Configure<HostOptions>(opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    ServiceLocationOptions locationOptions = config.GetSection(nameof(ServiceLocationOptions)).Get<ServiceLocationOptions>();
                    string url = locationOptions.HttpBase + "*:" + locationOptions.Port;
                    webBuilder.UseUrls(url);
                })
                .UseSystemd();
        }

In the meantime I am trying to trace all the Monitor.Enter() that I use to render serial the API endpoints that touch the state of the service and the inner structures, but in Windows seems all ok.
I am starting wondering if the issue in the call to SystemD. I would like to know what is really involved in a call to UseSystemD() but there is not so much documentation around.
I did just find [https://devblogs.microsoft.com/dotnet/net-core-and-systemd/] (https://devblogs.microsoft.com/dotnet/net-core-and-systemd/) by Glenn Condron and few quick notes on MSDN.
EDIT 1: To debug further I created a class to scan the threadpool using ClrMd.
My main service has an heartbeat (weird it is called Ping) as follows (not the add to processTracker.Scan()):
private async Task Ping()
    {
        await _containerServer.SyslogQueue.Writer.WriteAsync((
            LogLevel.Information,
            $"Monday Service active at: {DateTime.UtcNow.ToLocalTime()}"));
        string processMessage = ProcessTracker.Scan();
        await _containerServer.SyslogQueue.Writer.WriteAsync((LogLevel.Information, processMessage));
        _logger.DebugInfo()
            .Information("Monday Service active at: {Now}", DateTime.UtcNow.ToLocalTime());
    }

where the processTrackes id constructed like this:
 public static class ProcessTracker
    {
        static ProcessTracker()
        {
        }

        public static string Scan()
        {
            // see https://stackoverflow.com/questions/31633541/clrmd-throws-exception-when-creating-runtime/31745689#31745689
            StringBuilder sb = new();
            string answer = $"Active Threads{Environment.NewLine}";
            // Create the data target. This tells us the versions of CLR loaded in the target process.
            int countThread = 0;

            var pid = Process.GetCurrentProcess().Id;
            using (var dataTarget = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive))
            {
                // Note I just take the first version of CLR in the process. You can loop over
                // every loaded CLR to handle the SxS case where both desktop CLR and .Net Core
                // are loaded in the process.
                ClrInfo version = dataTarget.ClrVersions[0];
                var runtime = version.CreateRuntime();
                // Walk each thread in the process.
                foreach (ClrThread thread in runtime.Threads)
                {
                    try
                    {
                        sb = new();
                        // The ClrRuntime.Threads will also report threads which have recently
                        // died, but their underlying data structures have not yet been cleaned
                        // up. This can potentially be useful in debugging (!threads displays
                        // this information with XXX displayed for their OS thread id). You
                        // cannot walk the stack of these threads though, so we skip them here.
                        if (!thread.IsAlive)
                            continue;

                        sb.Append($"Thread {thread.OSThreadId:X}:");
                        countThread++;
                        // Each thread tracks a "last thrown exception". This is the exception
                        // object which !threads prints. If that exception object is present, we
                        // will display some basic exception data here. Note that you can get
                        // the stack trace of the exception with ClrHeapException.StackTrace (we
                        // don't do that here).
                        ClrException? currException = thread.CurrentException;
                        if (currException is ClrException ex)
                            sb.AppendLine($"Exception: {ex.Address:X} ({ex.Type.Name}), HRESULT={ex.HResult:X}");

                        // Walk the stack of the thread and print output similar to !ClrStack.
                        sb.AppendLine(" ------>  Managed Call stack:");
                        var collection = thread.EnumerateStackTrace().ToList();
                        foreach (ClrStackFrame frame in collection)
                        {
                            // Note that CLRStackFrame currently only has three pieces of data:
                            // stack pointer, instruction pointer, and frame name (which comes
                            // from ToString). Future versions of this API will allow you to get
                            // the type/function/module of the method (instead of just the
                            // name). This is not yet implemented.
                            sb.AppendLine($"           {frame}");
                        }
                    }
                    catch
                    {
                        //skip to the next
                    }
                    finally
                    {
                        answer += sb.ToString();
                    }
                }
            }
            answer += $"{Environment.NewLine} Total thread listed: {countThread}";
            return answer;
        }
    }

All fine, in Windows it prints a lot of nice information in some kind of tree textual view.
The point is that somewhere it requires Kernel32.dll and in linux that is not available. Can someone give hints on this? The service is published natively without .NET infrastructure, in release mode, arch linux64, single file.
thanks a lot
Alex

A: I found a way to skip the whole logging of what I needed from a simple debug session.
I was not aware I could attach also to a Systemd process remotely.
Just followed https://learn.microsoft.com/en-us/visualstudio/debugger/remote-debugging-dotnet-core-linux-with-ssh?view=vs-2022 for a quick step by step guide.
The only preresquisites are to let the service be in debug mode and have the NET runtime installed on the host, but that's really all.
Sorry for not having known this earlier.
Alex


text:
Q: Two FK to one PK I'm using SQL Server Express 2012 and trying to make two relatonships, two FKs from the same table to one PK in another table.
The relationship seems to work because it shows up in the database diagram but when I try to save the changes, I receive the following error:

'Members' table saved successfully
  'BookedResources' table
  - Unable to create relationship 'FK_BookedResourcesMemberId_MembersMemberId'.
  The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_BookedResourcesMemberId_MembersMemberId". The conflict occurred in database "resursBokning2", table "dbo.Members", column 'MemberId'.

MemberId in Members is the PK.
BookedResouce.EditedBy (FK) -> Member.MemberId (PK)
BookedResouce.MemberId (FK) -> Member.MemberId (PK)
Anybody know what this error is about?
I've read that it should be OK to have this kind of relationship so it should work.

A: The error occurs because maybe you use the same name for a foreign key twice, so change the name of the second to some other value, e.g.:
FK_BookedResourcesMemberId_MembersMemberId2

A: From the error you've provided, it looks like you tried to name both foreign keys the same. As @kinse suggests, give each foreign key relationship a unique name. Also, consider whether you need two foreign keys to the same table - it could indicate that your database model is incomplete.
I am making an assumption that Members wouldn't be editing other members, so EditedBy (a member) and MemberId appear to be unnecessary on the members table.


text:
Q: How to do If "WiFi disconnects then Bluetooth turns on" function? I have been searching endless to find an answer to this. I want to create an Android app that switches on the Bluetooth when the WiFi disconnects. Im starting to think i cannot be done.
I thought it would be something like IF WiFi=Inactive THEN Bluetooth=On <- In theory
However no where to be seen. i will be working in eclipse and compiling for the latest 4.4 if that helps.
Can anyone point me in the right direction. tell me what method im suppose to be using or how it can be done?
Anything else let me know.

A:
How to do If "WiFi disconnects then Bluetooth turns on" function?

So here is solution that came to my head:
At first you need to create mechanism that will listen for Wi-Fi network connection changes. Yes, i'm talking about BrodcastReceiver with proper intent-filters. So at first we need to define our receiver that will listen for network changes.
I mentioned intent-filters. At a glance intent-filters -> you can imagine them like "events" where each receiver can register one or events and when event is fired up and receiver is able to listen it (has assigned that event) will be immediately invoked.
Especially in you case you need this event (usually called action) that listens for Wi-Fi connectivity changes:
<action android:name="android.net.wifi.STATE_CHANGE" />

Same action you can retrieve through source-code:
WifiManager.NETWORK_STATE_CHANGED_ACTION

Then you have almost all things you need. But now you need to retrieve in our receiver actual state of Wi-Fi connectivity.
Answer is to use NetworkInfo class that wraps information about network. And this Object you are able to obtain from action above (see final source code at the end of answer).
And here it's pretty simple, when state of Wi-Fi will be disconnected you just enable Bluetooth.
Here is final source code:
public class NetworkReceiver extends BroadcastReceiver {

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

       // action when network connectivity changed
       if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {

          // gets network info from intent action
          NetworkInfo ni = intent.getParcelableExtra(
                                          WifiManager.EXTRA_NETWORK_INFO);

           // if network state is disconnecting or disconnected
           if (ni.getDetailedState().equals(DetailedState.DISCONNECTING)
                    || ni.getDetailedState().equals(DetailedState.DISCONNECTED)) {

              // turns Bluetooth on
           }
       }
   }
}

Notes:
1. I've done a few tests and now i know that in Android you are able to detect only these states of network with getState() and getDetailedState():
CONNECTED CONNECTING DISCONNECTED OBTAINING_IPADDR and CAPTIVE_PORTAL_CHECK All other states not working or works only some devices which is not very good but we can't do nothing (except Google Team).
2. Don't forget to add proper permissions to your manifest.xml to be able to read current state of network etc.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

3. I recommend you to look at BroadcastReceivers, Intents and Intent Filters and things related to Wi-Fi.
Hope it helps you.

A: It's pretty easy to determine when a network connection goes away. So you're half way there
The code:
public class NetworkStateReceiver extends BroadcastReceiver {

    private static Set<NetworkStateListener> listeners = new HashSet<NetworkStateListener>();

    public static void clearListeners() {
        listeners.clear();
    }
    public static void addListener(NetworkStateListener listener) {
        listeners.add(listener);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            NetworkInfo ni = (NetworkInfo) extras.get(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (ni != null) {
                for (NetworkStateListener listener : listeners) {
                    listener.stateChanged(ni);
                }
            }
        }
    }

    public interface NetworkStateListener {
        public void stateChanged(NetworkInfo networkInfo);
    }
}

In your manifest:
<receiver android:name="<your package>.NetworkStateReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        <action android:name="android.intent.action.PACKAGE_RESTARTED"/>
    </intent-filter>
</receiver>


text:
Q: kivy texture from array print many times I have a picture in an array from matlab.
I whant to print this picture in kivy.
# encoding: utf-8

import time
import matlab.engine

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
from kivy.graphics.texture import Texture

engine = matlab.engine.start_matlab("-nodesktop -noFigureWindows")

class kivyTest(Widget):

    def __init__(self):
        super(kivyTest, self).__init__()
        self.texture = Texture.create(size=(560, 420), colorfmt="rgb")
        time_eng, data_pict = engine.test_pict_data(4.0, 5.0, nargout=2)
        self.texture.blit_buffer(data_pict._data, bufferfmt="ubyte", colorfmt="rgb")
        with self.canvas:
            Rectangle(pos=self.pos, size=(560, 420), texture=self.texture)

    def on_touch_down(self, touch):
        x = touch.pos[0]
        y = touch.pos[1]
        time_eng, data_pict = engine.test_pict_data(x, y, nargout=2)
        self.texture.blit_buffer(data_pict._data, bufferfmt="ubyte", colorfmt="rgb")
        super().on_touch_down(touch)
        self.canvas.ask_update()

class my_app(App):
    title = 'Matlab raw data picture test'
    def build(self):
        return kivyTest()

if __name__ == '__main__':
    my_app().run()

the data_pict._data size is 560x420x3 uint8 in a 1D array
But when I print here is the result :

The normal result should be something like :

Do you have any idea about this behaviour ?

A: Ok I found the way
I fact the 1D data from matlab (pictureFrame.cdata._data) is not usable as this, we need to reorganize it with numpy and flat it when pass to the texture.
data_reorg = np.array(data_pict._data).reshape(data_pict.size, order='F')
self.texture.blit_buffer(data_reorg.ravel(), bufferfmt="ubyte", colorfmt="rgb")

This way is fast and efficient.


text:
Q: pyrocms files plugin variables I want to pull a url segment variable into the pyrocms file plugin call. it would look like

{{files:listing folder="[segment(2)]"}}

or something of the sort. What is the trick for embedding
{{url:segments..}}

inside
{{files:listing folder="…}}

I am trying to setup this up for a conditional query for a photo gallery

A: If you take a look at the PyroCMS Tags documentation you will see this clearly documented in the "Tag Attributes" section.

You may also use the output from other tags as attribute values in your tags. For example if you wanted the url segment to default to the slug of the currently viewed page you could do this:
{{ url:segments segment="1" default=page:slug }}
Here is an example showing the proper use of quotes and braces when the tag used as the attribute value has an attribute itself.
{{ url:segments segment="1" default={foo:bar value="baz"} }}
Tip: Omit quotes and braces when using tags as attribute values. The only exception is when the tag you are using as the attribute value has its own attributes.

So you can do that easily with:
{{ files:listing folder={url:segments segment="2"} }}

Basically you don't need to pretend it's a string if it's not. You can just send the foo:bar arguments through, but it if has attributes you can "group" the attributes with the call via a single { and }.
Simple right? :)


text:
Q: Reproduce Protovis Sunburst Labels with D3.js I'm migrating an older Rails/Protovis site to Django and D3.js.  I used a modified version of the Protovis sunburst (http://mbostock.github.com/protovis/ex/sunburst.html -- for my code see http://www.eafsd.org/assignments_sunbursts) and would like to recreate this in D3.js using the sunburst example (http://bl.ocks.org/4063423) as a baseline, but I have run into a wall with attaching labels to the arcs.
I have looked at several other SO questions including Aligning text inside circular arc d3js and Looking for a way to display labels on sunburst chart (could not find a working example), but I can't seem to get the textpath working.  If possible, it would be great to have the labels display radially as the text I'm displaying (18th Century diplomatic titles) can get quite long.
I have tried the following code from the example:
  d3.json("../assignment-by-type.json", function(error, root) {
      var path = svg.datum(root)
          .selectAll("path")
          .data(partition.nodes)
         .enter()
          .append("path")
          .attr("display", function(d) {
              return d.depth ? null : "none";
          }) // hide inner ring
          .attr("d", arc)
          .style("stroke", "#fff")
          .style("fill", function(d) {
              return color((d.children ? d : d.parent).name);
          })
          .style("fill-rule", "evenodd")
          .each(stash);

      /* my additions begin here */

      path.append("title")
          .text(function(d) {return d.name + ": " + d.size});

      path.append("text")
          .attr("dy", ".3em")
          .style("text-anchor", "middle")
          .append("textpath")
          .attr("class", "textpath")
          .attr("xlink:href", "#path")
          .text(function(d) { return d.name });

      /* end of what I've added, back to the example code*/

      d3.selectAll("input").on("change", function change() {
          var value = this.value === "count"
                ? function() { return 1; }
                : function(d) { return d.size; };

          path.data(partition.value(value).nodes)
              .transition()
              .duration(1500)
              .attrTween("d", arcTween);
      });
    });

The sunburst displays and the title show up on mouseover (although the inner ring doesn't have a size function so it returns as undefined).
Two other modifications I am trying to make: I can't find a D3js snippet that shows how to recursively compute the package sizes so that the inner nodes can show the total size of their associate leaves.
Finally, I can't figure out how to add my own color range.
I really appreciate your time.  Many thanks.


text:
Q: How to Create EAR file in RAD 7.5 I have checked out a dynamic web project from a CVS repository. But, there was no EAR file to check in. Now how can I create an EAR file for the project to deploy in WAS 6?
Also can I run my project in RAD without creating an .ear file? I am a newbie to Java EE projects.

A: In order to be able to export an EAR, you can add a new Enterprise Application project ( New > Enterprise Application project) and select your Web project as a Java EE module dependency.
This way you can export an EAR file that will contain a WAR file built from your Web project.

A: If you run the wizard for creating a new enterprise application (File->New), one of the options is to add an existing web project in your workspace into the application as you create it. You can then export the enterprise application as an EAR file ready to deploy into WebSphere Application Server or, if you have the test environment set up, you can just drag-and-drop it onto the server in the Servers view. To test your web application, right-click it and choose Run->Run on Server.

A: Try importing as project instead of EAR files


text:
Q: find rows with non-ascii values in a column How can I evaluate whether a column contains any non-ascii characters in mysql? In this case the charset  is actually latin1, so I'm just looking for high-byte chars.
I tried this:
select * from company where ticker regexp concat('[', x'7f', '-', x'ff', ']')

but this returns this error:
ERROR 1139 (42000): Got error 'invalid character range' from regexp

A: There must be an easier way to do this, but all the typical escapes I thought would work, didn't. So here is one, ugly solution:
select * from company
where ticker regexp(concat('[',char(128),'-',char(255),']'));


text:
Q: IOS webview callback on url change I have a UIWebView that is loaded with a url as soon as my application is loaded.
The webpage have different links that the user can go to.
I want to be able to see what links they are going to and also be able to change the url if they match a certain text. I do not care about ajax requests(they will not match the text).
Is there any function that i can use for this?

A: You must implement a UIWebViewDelegate. One of its methods is webView:shouldStartLoadWithRequest:navigationType:, which is called whenever the user navigates to another URL. From the NSURLRequest passed in you can get the URL. The last parameter (UIWebViewNavigationType) tells you what user action led to the request, e.g. click on a link in the page.


text:
Q: list comprehension fail, cannot show None a = []
b = []
c = []
d = []
a = input('Enter first  row (enter 0 for space): ')
b = input('Enter second row (enter 0 for space): ')
c = input('Enter third  row (enter 0 for space): ')
d = input('Enter fourth row (enter 0 for space): ')

start = [int(a[0]),int(a[2]),int(a[4]),int(a[6]),
         int(b[0]),int(b[2]),int(b[4]),int(b[6]),
         int(c[0]),int(c[2]),int(c[4]),int(c[6]),
         int(d[0]),int(d[2]),int(d[4]),int(d[6])]

[None if x==1 else x for x in start]

start

Here is my code, I try to input some value like (1 2 3 4) and save it into a list, then I want to use list comprehension to turn each 1 into None. But It can't change into None when I print it.

A: The list comprehension doesn't modify start in-place; you need a regular for to execute a series of assignment statements instead.
for i, x in enumerate(start):
    if x == 1:
        start[i] = None

A: Or, following chepner's answer, just try
start = [None if x==1 else x for x in start]
start


text:
Q: About local.php configuration and location for ZF2 application I have to take over a ZF2 PHP application which has not been developed by me initially.
I have been given a local.php file from the former developer. It contains some configuration elements.

*

*I believe I should put this copy in /config/autoload, correct?

*Do I need to perform an extra step to have it loaded by the application, if yes which?

A:

*

*I believe I should put this copy in /config/autoload, correct?

Correct.

Do I need to perform an extra step to have it loaded by the application, if yes which?

You shouldn't need to do anything. The ZF2 skeleton application (which is usually used as the basis for all ZF2 apps) does this by default. The relevant code is here: https://github.com/zendframework/ZendSkeletonApplication/blob/master/config/application.config.php#L29 - so you can see if your application has something similar.


text:
Q: Images appear in Chrome, but not in IE Was handed this little gem of a site this morning. The site works great in Chrome, but IE9 seems a bit buggy.
The banner and 4 link buttons somehow "vanish" when viewed in IE9. They appear breifly, for a second, and then POOF! Gone!
Located here:
http://www.cityplaceselfstorage.com/Calidus/calidus.html
They all seem to be img src tags as follows:

              <map name="map1" id="map1">
                  <area href="Calidus_Profile.html"
                        title="Calidus_Profile.html" alt="Calidus_Profile.html"
                        coords="5, 3, 220, 132" />
              </map>

Of course, there isn't a "tinyText" class in the css file. But when deleting the reference inside one of the div tags didn't make the image appear, either.
What's even stranger - the images appear in IE when I open the html file locally.
Can anyone give me a clue as to what might be going on?
Thanks,
Jason

A: After a semi-exhaustive search, I found someone claiming that IE doesn't like .png images. So I converted them all to .jpg format.
Images show up fine in IE9, so long as they're jpg's.
FYI


text:
Q: Angular2: Need to add provider in component for dependency on service? I'm having some trouble understanding the logic that Angular2 uses when it comes to dependency injection. This is my situation:
app.component.ts:
import {Component} from 'angular2/core';
import {Demo1Service} from './demo-1.service';

@Component({
    selector: 'app',
    template: `<div>test template</div>`,
    providers: [Demo1Service]
})
class AppComponent {
    constructor(private _demo1Service: Demo1Service) {}
}

export {AppComponent};

demo-1.service.ts
import {Injectable} from 'angular2/core';
import {Data1Store} from './data-1.store';

@Injectable()
class Demo1Service {
    constructor(private _data1Store: Data1Store) {}
};

export {Demo1Service};

data-1.store.ts
import {Injectable} from 'angular2/core';

@Injectable()
class Data1Store {}

export {Data1Store};

http://plnkr.co/edit/4aBNbAxtHbUvVqxPRUbv?p=preview
If you run this plunker you will see that Angular needs a provider for the Data1Store to be defined in the AppComponent. In order to have some separation of concerns, I would prefer that the AppComponent doesn't need to know about the existence of the Data1Store.
Is there something I'm here?

A: In fact, the provider needs to present when executing the Demo1Service service. Because of hierarchical injectors, it's not mandatory to have the corresponding provider defined at the component level.
This can also be done for the whole application or within a parent injector. Defining this provider when bootstrapping your application seems to be what you need:
bootstrap(AppComponent, [ Demo1Service, Data1Store ]);

This way you don't need to define your service providers within the providers attribute of your component
Here is an overview of all these elements and there relations:
Application
     |
AppComponent  --- Demo1Service --- Data1Store

In such application, we have two injectors:

*

*The application injector that can be configured using the second parameter of the bootstrap function

*The AppComponent injector that can be configured using the providers attribute of this component. It can "see" elements defined in the application injector. This means if a provider isn't found in this provider, it will be automatically look for into this parent injector. If not found in the latter, a "provider not found" error will be thrown.
This question could give you more details about how hierarchical injectors of Angular work:

*What's the best way to inject one service into another in angular 2 (Beta)?


text:
Q: Is the Facebook Insights OData feed gone? I'm looking to pull Insights data into excel via oData. The site that everyone is linking to is here - also referenced by this URL - but as far as I can tell there's no server at that address.
Is the Facebook Insights oData feed gone?


text:
Q: Howto get a callback on JS function execution using a Spy I want to spy on a function, then execute a callback upon function completion/initial call.
The following is a bit simplistic, but shows what I need to accomplish:
//send a spy to report on the soviet.GoldenEye method function
var james_bond = sinon.spy(soviet, "GoldenEye");
//tell M about the superWeapon getting fired via satellite phone
james_bond.callAfterExecution({
    console.log("The function got called! Evacuate London!");
    console.log(test.args);
});

Is it possible to do this in Sinon? Alternate libraries welcome as well if they solve my problem :)

A: It's clunky but you can:
//send a spy to report on the soviet.GoldenEye method function
var originalGoldenEye = soviet.GoldenEye;

var james_bond = sinon.stub(soviet, "GoldenEye", function () {
  var result = originalGoldenEye.apply(soviet, arguments);

  //tell M about the superWeapon getting fired via satellite phone
  console.log("The function got called! Evacuate London!");
  console.log(arguments);
  return result;
});

A: You have to stub the function. From the docs:

stub.callsArg(index);
Causes the stub to call the argument at the
  provided index as a callback function. stub.callsArg(0); causes the
  stub to call the first argument as a callback.

var a = {
  b: function (callback){
    callback();
    console.log('test')
  }
}

sinon.stub(a, 'b').callsArg(0)
var callback = sinon.spy()
a.b(callback)

expect(callback).toHaveBeenCalled()
//note that nothing was logged into the console, as the function was stubbed


text:
Q: variable-length lists in ksql In KSQL, one can use EXTRACTJSONFIELD for nested structures, but I don't see how to deal with variable-length lists. For example:
{"id":1,"quux":[{"x":1,"y":2},{"x":3,"y":4},{"x":5,"y":6}]}

I can deal with quux as a varchar for the basic stream,
create stream mystream (id bigint, quux varchar)
with (kafka_topic='mytopic', value_format='json')

but I'd like to be able to turn this into a table with:
quuxid x y
1      1 2
1      3 4
1      5 6

How do I deal with variable-length lists in KSQL?

A: This isn't currently possible in KSQL.
As you've seen, you can access the array data by index specifically: Populate test data:
echo '{"id":1,"quux":[{"x":1,"y":2},{"x":3,"y":4},{"x":5,"y":6}]}' | \
kafkacat -b localhost:9092 -t quux

Check message in KSQL:
ksql> print 'quux' from beginning;
Format:JSON
{"ROWTIME":1528791985250,"ROWKEY":"null","id":1,"quux":[{"x":1,"y":2},{"x":3,"y":4},{"x":5,"y":6}]}

Create stream:
create stream mystream (id bigint, quux varchar) \
with (kafka_topic='quux', value_format='json');

Query stream:
ksql> SET 'auto.offset.reset' = 'earliest';
Successfully changed local property 'auto.offset.reset' from 'earliest' to 'earliest'
ksql>
ksql> select * from mystream;
1528791985250 | null | 1 | [{"x":1,"y":2},{"x":3,"y":4},{"x":5,"y":6}]

Create stream with array:
ksql> CREATE STREAM mystream2 (id bigint, quux array<varchar>) with (kafka_topic='quux', value_format='json');

 Message
----------------
 Stream created
----------------

Access individual items by index:
ksql> SELECT quux[0], EXTRACTJSONFIELD(quux[0],'$.x') AS X, EXTRACTJSONFIELD(quux[0],'$.y') AS Y from mystream2;
{"x":1,"y":2} | 1 | 2

But you're looking for the equivalent of an EXPLODE function, which doesn't yet exist in KSQL.
Related github issues:

*

*https://github.com/confluentinc/ksql/issues/1324

*https://github.com/confluentinc/ksql/issues/527

*https://github.com/confluentinc/ksql/issues/1413 (which I've just seen you've logged, thank you :) )


text:
Q: What is the type for a function that takes a string and returns a string or takes void and returns void? I have the following function;
const capitalize = (input) =>
    (!(typeof input === 'undefined'))
        ? input
            .split(' ')
            .map(capitalizeWord)
            .join(' ')
        : undefined

This either takes a string and returns a string or takes undefined and returns undefined, but never takes a string and returns undefined or takes undefined and returns a string. My thought was the type should be something like (void => void) & (string => string) but that doesn't do at all what I want; Flow gets concerned that I haven't specified going into capitalize whether the input is a string or undefined, when what I want it to do is effectively dispatch to the correct type. When I let flow just infer the type, it infers (void | string) => (string | void), which is too broad. What is the correct signature for this?

A: You can define generic as string or void:
const capitalize = <T: string | void>(input: T): T =>
        (!(typeof input === 'undefined')) ? input
            .split(' ')
            .join(' ')
        : input

However, it should return passed arg, not undefined. Try.


text:
Q: Monitoring compressing files What would be the most common way to monitor the progress of compressing files? Is there a way to estimate the time it will take to compress a file or a directory? I'm trying to implement a progress bar for an application in java that zip files.
Thanks in advance for your answers!

A: You cannot estimate time. It depends on too many parameters and might vary from one second to the next.
It is tempting to monitoring the output on the zip stream but you cannot guess in advance of much space the compressed file will take. So it won't work either.
The best way would be to browse all the files you're going to compress, sum their sizes and as you stream data into the zip, move the progress bar proportionally.
I would also suggest to add a counter like 345/554 files so that you also have an idea of the number of files.
If you want more specific suggestions, you'll need to share some code of your attempt.


text:
Q: Last digit of the power of 2 numbers without performing the operation in javascript I would like to know how to find the units digit of a number raised to another number without calculating the result of the operation, i.e 5**7 = 78125, so I want to write a function that returns 5 as the last digit of the operation.

A: This link offer a simple algorithm that explains how to deal with such problem.

Identify the units digit in the base 'x' and call it say 'l'. {For
  example, If x = 24, then the units digit in 24 is 4. Hence l = 4.}
  Divide the exponent 'y' by 4. If the exponent y is exactly divisible
  by 4. i.e, y leaves a remainder 0 when divided by 4. Then, the units
  digit of pow(x,y) is 6, if l = 2,4,6,8. the units digit of  pow(x,y) is 1,
  if l =3,7,9. If y leaves a non-zero remainder r, when divided by 4
  (i.e y = 4k + r). Then, the units digit of  pow(x,y) = pow(I,r) .

A basic implementation of this algorithm :
function getLastDigit(x, y) {
  const I = x % 10;
  const r = y % 4;
  if (r === 0) {
    if (I === 2 || I === 4 || I === 6 || I === 8) {
      return 6 % 10;
    }
    if (I === 3 || I === 7 || I === 9) {
      return 1 % 10;
    }
  }
  return I ** r % 10;
}
console.log(getLastDigit(2019, 2020));


text:
Q: Poincaré invariant corresponds to area? In this paper(equation 34) click me it says that if we have a symplectic egg, then the area of a $(x_i,p_i)$ clone intersected with the egg is given by the poincaré invariant
$\int p dx = \int_0^{2 \pi} p_i(t) x_i'(t) dt,$ where $p_i,x_i : [0,2\pi] \rightarrow \mathbb{R}$ are a paramerization of the boundary of the area of intersection.
Unfortunately, I don't see how this number is related to the respective area.

A: There seems to be a sign discrepancy, but this is an application of Green's Theorem to give the area of a plane region bounded by a closed curve.


text:
Q: class-transformer returning undefined I am new to using the class-transformer. I created a simple product class and JSON string to load a Product. However, I get undefined, even though I see the output when I log the result like the transformation was successful. I removed the readonly, but it made no difference. Please help, I have spent so much time. The problem is reading the JSON from a json file does not work.  When I use the JSOn as follows:
   let prodJson = {
                   name: 'MyProduct,
                   productId: 'POOA',
                   description: 'A product'
                  }

etc. this works. If I read the JSON from a file, it doesn't.
 export class Product{
   @Expose()
   public readonly name: string;
   @Expose()
   public readonly productId?: string;
   @Expose()
   public readonly description?: number;
  }

   const productJson =   {\n" +
       "     \"name\": \"Aerosol\",\n" +
       "     \"productId\": \"ARSL\",\n" +
       "     \"description\": \"Apply to living room\"\n" +
      "}"

      createProduct(productJson: string){
         return plainToInstance(Product, productJson);
      }

      const product = createProduct(productJson);
      console.log('Product', product); // undefined

A: createProduct(productJson: string){
  return plainToInstance(Product, JSON.parse(productJson));
}

plainToInstance: This method transforms a plain javascript object to instance of specific class. The second parameter not a json string. it should be an object.


text:
Q: How to modify standalone.xml in JBOSS so that it is visible from outside? I have an Ubuntu 14.04 image and i have installed JBOSS. I have a static ip and i want to access the admin console of JBOSS from another pc. I have changed standalone.xml like this:
    <interface name="management">
        <inet-address value="${jboss.bind.address.management:128.x.x.x}"/>
    </interface>
    <interface name="public">
        <inet-address value="${jboss.bind.address:128.x.x.x}"/>
    </interface>
    <interface name="unsecure">
        <inet-address value="${jboss.bind.address.unsecure:128.x.x.x}"/>
    </interface>

When i start JBOSS everything seems ok, but when i try to access JBOSS from my computer (http://128.x.x.x:9990/console) i get that the website is not available. I can ping 128.199.35.98, which the ip of the ubuntu server, where JBOSS is installed.

A: When changing the address and or port the server listens on you need to ensure the firewall allows that port to be accessed.
Something like
sudo iptables -A INPUT -p tcp --dport 9990 -j ACCEPT


text:
Q: How to recover files from index I accidentally erase files.
Fortunately, I have added those to index.
Please tell me how to recover those files to working tree, without commiting.

A: 2014: git checkout-index will restore deleted files. It will NOT change the content of existing files.
(unless, as commented, using the -f/--force option)
Charles mentions a simpler solution, which can also be used to restore the content of files which existing in the working copy to their last indexed state:
git checkout -- the_erased_file

But that can silently overwrite an existing file, so don't make mistake.
(git checkout-index, by default, won't overwrite)

2020, Git 2.23+: use the git restore command:
You can specify the source (index), default is the index and destination (working tree).
git restore -- aFile

That will restore the working tree from the index.
git restore


text:
Q: Nginx reverse proxy to another nginx server serving static files I have an Nginx server hosting a web app which works fine when directly accessed. Its config is below
server {
    listen 8000 default_server;

    listen [::]:8000 default_server ipv6only=on;

    root /data/www/ ;
    server_name server1.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location /app/ {

    }
}

Now i have to serve this app from another Nginx server So i setup the reverse proxy like below
server {
    listen 80 default_server;

    listen [::]:80 default_server ipv6only=on;

    root /data/www/ ;
    server_name server2.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location /app/ {
        proxy_pass http://server1.com:8000/app/;
    }
}

When i access the app from server2 i am getting errors like below for example when i am accessing http: server2.com/app/css/app.css

[error] 6601#0: *1 open() "/data/www/app/css/app.css" failed (2: No such file or directory)

and no errors in serv er1 logs. Why is nginx looking for static files in server2 when i have set it to reverse proxy to server1 same setup works fine in apache with

ProxyPass /app/ http:server1:8000/app/
ProxyPassReverse /app/ http:server1:8000/app/

What am i missing ?

A: You have regexp location that matches your request /app/css/app.css and intercepts request from proxy. That's how regexp locations works. To prevent this use ^~ modifier for your app location:
location ^~ /app/ {
    proxy_pass ...;
}

This will prevent regexp location from matching.
Documentation: http://nginx.org/r/location


text:
Q: Downloading a pdf from a url using java I am trying to download pdf from a url using java.
I am using the following code for the same.  I am able to download the pdf.
But the problem is that I am not able to read the pdf using the adobe reader because the content type of the url is application/pdf ; charset= utf-8.
Although for all the urls whose content type is not the same as above, I am able to download as well as read the pdf.
public class PdfDownloading
{
    public static void DownloadPDFFromURL(String link)
    {
        try
        {
            URL url = new URL(link);
            InputStream in = url.openStream();
            FileOutputStream fos = new FileOutputStream(new File("E:\\KOLDump\\charles_hicks\\pdfs\\"+"hello"+".pdf"));
            int length = -1;
            byte[] buffer = new byte[50000];// buffer for portion of data from connection
            while ((length = in.read(buffer)) > -1) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            in.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public static void main(String [] args)
    {
        DownloadPDFFromURL("http://www.amjmed.com/article/S0002-9343(06)00676-0/pdf");
    }

}

The url from which I am not able to download the pdf is given in the code itself.


text:
Q: how to use base schema to child schema in mongoose I have parent schema which is common field for all the child schema. How to extend parent to child schema?
parent schema
const BaseSchema = new mongoose.Schema({
  eventId: {
    type: dataTypes.ObjectId,
    required: false
  },
  eventType: {
    type: dataTypes.String
  },
  eventSource: {
    type: dataTypes.String
  },
 })

child schema
const ChildSchema = new mongoose.Schema({
  eventId: {
    type: dataTypes.ObjectId,
    required: false
  },
  eventType: {
    type: dataTypes.String
  },
  eventSource: {
    type: dataTypes.String
  },
age : {
    type: dataTypes.String
  },
name : {
    type: dataTypes.String
  },
place : {
    type: dataTypes.String
  },
 })

The question is eventId,eventType,eventSource is common for all the schema so tires to create one common for above fields. I creadted that schema as BaseSchema. Is possible to use like this? How to extend the base to child?


text:
Q: how to pull a string from a list of objects in python
import os; import time;

not_command_error = "error: not an command"
empty_error = "error: file empty"

def read(file):
  e = open(file, "r")
  b = e.readlines()
  e.close()
  return b

code_file = "put your code here"

e = read(code_file)
if e == []:
  print("\033[0;37;41m",empty_error)
  time.sleep(90000)
count = len(e)
print(count)
g = 0
l = 0
while True:

  l+= 1
  t = open(code_file, "r")
  y = t.readlines(l)
  t.close()
  k = len(y)
  print(y[k])
  u = y[k]

  g+= 1
  if count == g:

    break

this is my code, and I get and index out of range error, any help?
i tried changing the format and it still didn't work.
i get index out of range error, do i not use a variable?

A: This part of your code will throw an index out of range error:
k = len(y)
print(y[k])

Indices for lists in Python go from 0 to len(x) - 1, so to access the last element, k should equal len(y) - 1.
Even better (thanks, @MarkK!), you can use negative indices to access the end of the array:
print(y[-1])


text:
Q: SoX batch file... encoding in u-law 8000 kHz I am trying to make a batch file for SoX, and I have the standard command line code working...
sox.exe -V test-input-file.wav -e u-law -r 8000 -c 1 test-output-file.wav

Here is the batch file I have created...
cd %~dp0
mkdir converted
FOR %%A IN (%*) DO sox %%A "converted/%%~nxA" -e u-law -r 8000 -c 1
pause

Any ideas where I am going wrong?
Thanks!

A: Assuming your initial batch command worked, see if this changes anything:
@echo off
cd /d "%~dp0"
mkdir converted 2>nul
FOR %%A IN (*.wav) DO sox.exe -V "%%A" -e u-law -r 8000 -c 1 "converted\%%~nxA"
pause


text:
Q: Нужно создать уникальную ссылку вида: "../message/ftr45e32fgv56d2" Почти решил задачу сам. Так как модели Message у меня поле body шифруется в AES я переписал метод to_param body - шифрофанный текст вида wuTekBX7p0K+olP6Vd/8Jw==$okRXvvSB1ZRRuhxF3O9EIg==.
def to_param
    "#{id}-#{body.tr('^A-Za-z0-9', '')[0..12].insert(3, self.id.to_s.chars.each_slice(2).map(&:join).first).insert(9, self.id.to_s.chars.each_slice(2).map(&:join).last).parameterize}"
end

Да смотрится немного странно:)
В конечном итоге ссылка получается /messages/2-wut2ekbx72p0kol
Но нужно сделать без id в начале и чтобы была уникальной.

A: Перед созданием записи в таблицу messages генерируй нужный код, его пиши в отдельное поле в таблице, например link_id. По нему как раз будешь проверять уникальность. Естественно, на него нужен индекс.
  before_create :generate_link_id

  def generate_link_id
    self.link_id = SecureRandom.hex(10)
    self.link_id = SecureRandom.hex(10) while Message.find_by_link_id(self.link_id)
  end

route будет соответственно
get "/message/:link_id" => "messages#show"

По нему и будешь искать message в контроллере.
def show
  @message = Message.find_by_link_id! params[:link_id]
end

Пытаться изобразить что-то из шифрованного body - так себе затея. В теории можно, конечно, придумать некоторую уникальную hash-функцию, но зачем?


text:
Q: Sound Visualizer for Wave Files in Silverlight My program currently plays a .wav file using MediaElement in wp7.
I want to write a extremely simple visualizer for it (for example a number that indicates the amplitude of the wave). However I have no idea on how I should obtain the raw media information from the MediaElement.
I have searched around, and so far have ended up with the Salus MediaKit (only for MP3), Beat detection (which involves complex algorithms) and WaveControl, which does not display in real time.
Could someone more well versed in audio processing point me towards a approach I could take?

A: Don't think you can obtain the raw audio data from the media element. Need access to the audio file ahead of time to do your calculations and then use GetSampleAsync of the MediaStreamSource class to send audio samples to your MediaElement. Can find documentation on MSDN here.
Think you can still use the Saluse Media Kit as a reference as it is first decoding the mp3 file into raw audio data and then doing its operations on that. Can look in the RawMP3MediaStreamSource class to reference this. WAV files are uncompressed, so you should be able to calculate your amplitude from it after you strip out any header information. A good thing to read is how uncompressed audio (PCM) is stored.


text:
Q: Create a Map with keys from 1 to 100 odd numbers and Values from even numbers from 1 to 100 in Kotlin Thanks in advance! It's the first time I am asking in StackOverflow

A: Keys and values in ascending order:
val result = (1..100 step 2).associateWith { it + 1 }

println(result)   // prints {1=2, 3=4, 5=6, 7=8, ..., 99=100}

If you need only the keys in ascending order and the values shuffled:
val result = (1..99 step 2)
  .zip((2..100 step 2).shuffled())
  .toMap()

println(result)   // {1=74, 3=18, 5=40, 7=14, 9=76, 11=34, ..., 99=38}

If you need both the keys and the values shuffled:
val result = (1..99 step 2).shuffled()
  .zip((2..100 step 2).shuffled())
  .toMap()

println(result)   // {23=34, 39=70, 61=24, 77=36, 83=86, ..., 49=74}


text:
Q: How can i design a DB where the user can define the fields and types of a detail table in a M-D relationship? My application has one table called 'events' and each event has approx 30 standard fields, but also user defined fields that could be any name or type, in an 'eventdata' table. Users can define these event data tables, by specifying x number of fields (either text/double/datetime/boolean) and the names of these fields. This 'eventdata' (table) can be different for each 'event'.
My current approach is to create a lookup table for the definitions. So if i need to query all 'event' and 'eventdata' per record,  i do so in a M-D relaitionship using two queries (i.e. select * from events, then for each record in 'events', select * from 'some table').
Is there a better approach to doing this? I have implemented this so far, but most of my queries require two distinct calls to the DB - i cannot simply join my master 'events' table with different 'eventdata' tables for each record in in 'events'.
I guess my main question is: can i join my master table with different detail tables for each record?
E.g.
SELECT E.*, E.Tablename
FROM events E
LEFT JOIN 'E.tablename' T ON E._ID = T.ID

If not, is there a better way to design my database considering i have no idea on how many user defined fields there may be and what type they will be.

A: There are four ways of handling this.

*

*Add several additional fields named "Custom1", "Custom2", "Custom3", etc.  These should have a datatype of varchar(?) or similiar

*Add a field to hold the unstructured data (like an XML column).

*Create a table of name /value pairs which are associated with some type of template.  Let them manage the template.  You'll have to use pivot tables or similiar to get the data out.

*Use a database like MongoDB or another NoSql style product to store this.
The above said, The first one has the advantage of being fast but limits the number of custom fields to the number you defined.  Older main frame type applications work this way. SalesForce CRM used to.
The second option means that each record can have it's own custom fields.  However, depending on your database there are definite challenges here.  Tried this, don't recommend it.
The third one is generally harder to code for but allows for extreme flexibility.  SalesForce and other applications have gone this route; including a couple I'm responsible for.  The downside is that Microsoft apparently acquired a patent on doing things this way and is in the process of suing a few companies over it.  Personally, I think that's bullcrap; but whatever.  Point is, use at your own risk.
The fourth option is interesting.  We've played with it a bit and the performance is great while coding is pretty darn simple.  This might be your best bet for the unstructured data.

A: Those type of joins won't work because you will need to pivot the eventdata table to make it columns instead of rows. Therefore it depends on which database technology you are using.
Here is an example with MySQL: How to pivot a MySQL entity-attribute-value schema

A: My approach would be to avoid using a different table for each event, if that's possible.
I would use something like:
Event (EventId, ..., ...)
EventColumnType (EventColumnTypeId, EventTypeId, ColumnName)
EventColumnData (EventColumnTypeId, Data)

You are them limited to the type of data you can store (everything would have to be strings, for example), but you the number of events and columns are unrestricted.

A: What I'm getting from your description is you have an event table, and then a separate EventData table for each and every event.
Rather than that, why not have a single EventCustomFields table that contains a foreign key to the event table, a field Name (event+field being the PK) and a field value.
Sure it's not the best. You'd be stuck serializing the value or storing everything as a string. And you'd still be stuck doing two queries, one for the event table and one to get it's custom fields, but at least you wouldn't have a new table for every event in the system (yuck x10)
Another, (arguably worse) option is to serialize the custom fields into a single column of the and then deserialize when you need. So your query would be something like
Select E.*, C.*
From events E, customFields C
Where E.ID = C.ID

A: Is it possible to just impose a limit on your users? I know the tables underneath Sharepoint 2007 had a bunch of columns for custom data that were just named like CustomString1, CustomDate2, etc. That may end up easier than some of the approaches above, where everything is in one column (though that's an approach I've taken as well), and I would think it would scale up better.

A: The answer to your main question is: no.  You can't have different rows in the result set with different columns.  The result set is kind of like a table, so each row has to have the same columns.  You can fake it with padding and dummy columns, but that's probably not much better.
You could try defining a fixed event data table, with (say) ten of each type of column.  Then you'd store the usage metadata in a separate table and just read that in at system startup.  The metadata would tell you that event type "foo" has a field "name" mapped to column string0 in the event data table, a field named "reporter" mapped to column string1, and a field named "reportDate" mapped to column date0.  It's ugly and wastes space, but it's reasonably flexible.  If you're in charge of the database, you can even define a view on the table so to the client it looks like a "normal" table.  If the clients create their own tables and just stick the table name in the event record, then obviously this won't fly.
If you're really hardcore you can write a database procedure to query the table structures and serialize everything to a lilst of key/type/value tuples and return that in one long string as the last column, but that's probably not much handier than what you're doing now.


text:
Q: Why does qt-creator need to connect to google-analytics? I just installed qt-creator to work on non-qt C++ projects. The installed version is 2.5.0 (Based on Qt 4.8.2 32-bit)
If I click on any of these pages:

I get this error:

I realized that /etc/hosts file has the following entry:
127.0.0.1  www.google-analytics.com

I don't want to remove the entry from the hosts file because it's always been there along with thousands of other similar adservices/porn/malware addresses.
I do not intend to say that qt-creator is looking to create problems in my computer, but I am genuinely interested to know why qt-creator needs to connect to google-analytics? Can this be disabled and qt-creator can still be functional?

A: It is said by Qt employees that Google Analytics code used to be included in Qt documentation (and pages you are viewing as part of it), but was removed afterwards (source).
Try upgrading Qt creator to the most recent version (2.5.2 in repos / 2.6.0 http://qt-project.org/downloads) and see if this solves your problem.
Apart from that, I'd say pretty much any IDE tries to collect usage statistics if you allow it to. Check out if this can be configured in Qt Creator.

A: I managed to solve my problem installing the qtcreator-doc package:
sudo apt-get install qtcreator-doc


text:
Q: How can I move only a certain body part of humanoid with cursor in Unity? For example a humanoid is standing still and one hand is grabbed with the cursor and cursor is moved around to make the humanoid do a waving motion. In this case the hand and the arm will only be moved but the rest of the body stays still.
How can I achieve this? How do I add a collider between each joint? or do I need to use ragdoll mechanics? I have no idea how to achieve this. If someone could send me in the right direction. I just need to basically be able to turn a humanoid in to a puppet where any parts can be grabbed and moved with the cursor.


text:
Q: jquery html() is decoding html entities by default? I dont know why on earth jquery html() is doing this, but after i do
$('html').html()

i get "&copy" automatically converted to ©
anyway to avoid this? I need to dump the html of the page using javascript and dont need this useless conversions that are screwing up the html.

A: This really isn't the jQuery, or even JavaScript for that matter.
The browser will hold its own normalised representation of the underlying DOM. It will bear a close resemblence the the document itself, but character decoding (like the above) will be preserved.
Have a read of the following:
http://www.brainjar.com/dhtml/intro/
http://bytes.com/topic/javascript/answers/146257-body-innerhtml-issue
I'm afraid there is no way around this as far as I am aware.

A: jQuery should not. check what you really get using in FF firebug.
console.log($('html').html());


text:
Q: C# Changing incoming and outgoing TCP Communication What is the best way of reading, changing, and resending tcp communications?
For instance i have a server application that tells a master server it's alive sending a packet over TCP on port 3209. It sends out "I'm alive, my ip is xxx.xxx.xxx.xxx and I have currently 3 clients connected to me." the master server then responds, "Hello xxx.xxx.xxx.xxx i see you there."
Whats the best way of MITM of the server sending its packet to the master server? I would like to be able to change "i'm alive," to something like, "I'm changed," or even "currently 3 clients connected" to "currently 0 clients connected"
Any ideas appreciated, thank you.

A: There's no need to send out that kind of message.
First of all, TCP is connection oriented, so as long as you have a connection you'll be alive.
You can check if you're still connected by using the TCPClient.Connected property.
Secondly, TCP runs over IP so in the IP header you can find the sender IP (is in the socket properties) so no need to send the IP neither.
You can check the remote IP address by using TCPClient.Socket.RemoteEndPoint property.
Finally, the only thing you might be interested in telling is the "3 clients connected part" wich can be coded as a simple integer transmision. That is, a 4 bytes hearbeat.
Getting in the middle of the connection IS tricky and has nothing to do with communication protocols. And honestly it's a hell of a job, if there's a connection already present you'll have to find a way to make the client or the server drop it and then have the server reestablish it to your MIDM. More though, if the connection is made directly to an IP address you'll have to mess with the router tables somehow for the attact to be succesful, if it's not maybe DNS poisoning will work for you... anyway not an easy task.
Those are only ideas... it depends on the class of network, if you have physical access or not, if the client and the server trust each other (as in if they are your applications) and so on... I assume all this is ethical or educational at least... :)

A: Have a look at SharpPcap or any other packet capturing/injecting library.
In order to MITM, you'll have to force the client to think you're the server and the server to think you're the client. For that, you'll have to send ICMP packet to both machines as described here. Then, you will capture the packets, modify them and inject them to the network (with the correct MAC address).

A: Pick a different tool - this is too low level a kind of thing to attempt in C#. This kind of thing is achieved (on Vista and later) using the Windows Filtering Platform


text:
Q: print search term with line count Hello bash beginner question. I want to look through multiple files, find the lines that contain a search term, count the number of unique lines in this list and then print into a tex file:

*

*the input file name

*the search term used

*the count of unique lines

so an example output line for file 'Firstpredictoroutput.txt' using search term 'Stop_gained' where there are 10 unique lines in the file would be:
Firstpredictoroutput.txt Stop_gained 10

I can get the unique count for a single file using:
grep 'Search_term' inputfile.txt | uniq -c | wc -l | >>output.txt

But I don't know enough yet about implementing loops in pipelines using bash.
All my inputfiles end with *predictoroutput.txt
Any help is greatly appreciated.
Thanks in advance,
Rubal

A: You can write a function called fun, and call the fun with two arguments: filename and pattern
$ fun() { echo "$1 $2 `grep -c $2 $1`"; }
$ fun input.txt Stop_gained
input.txt Stop_gained 2

A: You can use find :
find . -type f -exec sh -c "grep 'Search_term' {} | uniq -c | wc -l >> output.txt" \;

Although you can have issue with weird filenames. You can add more options to find, for example to treat only '.txt' files :
find . -type f -name "*.txt" -exec sh -c "grep 'Search_term' {} | uniq -c | wc -l >> output.txt" \;

A: q="search for this"
for f in *.txt; do echo "$f $q $(grep $q $f | uniq | wc -l)"; done > out.txt


text:
Q: How to quote an email address in Bibtex?
Possible Duplicate:
Citing personal correspondence with function of cited person via email?

How do you guys quote the email address of an author in your library section? What bst styles and bib packages do you use? How do you code the library entry?
That's how my German university wants to have it like (follows the rule "DIN1505").
Morgner, U. <morgner@uni-muenster.de> ; Steinmeyer, G. ; Mitschke,
F.: Systematic evaluation and prediction of the pulse width of
synchronously pumped lasers. URL:
<http://link.springer.de/link/service/journals/00340/bibs/8066002/80660145.htm>,
verfügbar am 1.3.1998

This is a weblink, I also have a book, where I want to quote the email of the author. According to this template, there is an email field, which however is not used by Bibtex.
By the way, I use the natbib package and alphadin.bst for DIN1505 support.

A: My suggestion probably won't give the result you'd like, but try something like:
@article{MSM98,
 author = "Morgner, U. and Steinmeyer, G. and Mitschke, F.",
 title = "Systematic evaluation and prediction of the pulse width of
          synchronously pumped lasers",
 year = "1998",
 note = "{\tt morgner@uni-muenster.de}"
}

otherwise, try
@article{MSM98,
 author = "Morgner, U. {\tt morgner@uni-muenster.de} and Steinmeyer, G. and Mitschke, F.",
 title = "Systematic evaluation and prediction of the pulse width of
          synchronously pumped lasers",
 year = "1998"
}

Cheers


text:
Q: Use of the '{' character in VBA I am trying to write a similar function in VBA:
=VLOOKUP("EN878",CHOOSE({1,2},A2:B5,D2:E5),2,False)

In particular, What is the correct way of using the {} character in VBA?
Every time I try, I get "Compile error: Invalid Character"
My code:
Variables
Table3 = Workbooks("gangstar.xlsx").Worksheets("60 in August 2016-26082016-1137").Range("A1:A1000")
Table2 = Workbooks("gangstar.xlsx").Worksheets("60 in August 2016-26082016-1137").Range("H1:H1000")

For Each cl In Table1
  Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Choose({1,2}, Table2, Table3), 2, False)
  Dept_Row = Dept_Row + 1
Next cl

I am able to use the VLOOKUP with CHOOSE fine in the Excel spreadsheet.

A: Try the following, which doesn't require modification or recalculation of any cells on the Worksheet:
WorksheetFunction.VLookup("EN878", WorksheetFunction.Choose(Array(1, 2), Range("A2:B5"), Range("D2:E5")), 2, False)

A: If you are trying to decide which table to use as Vlookup array you can use IIf function.
Like:
Application.WorksheetFunction.VLookup(cl, IIf(cl.column=1, Table2, Table3), 2, False)

A: I would recommend using Sheet1.Cells(myRow, myCol).Formula = "=VLOOKUP(...)" followed by Sheet1.Cells(myRow, myCol).Calculate.

A: Not an answer but what the OP is doing is not as simple as it appears.
Given this data:

And this code:
Sub Tester()

    Dim r

    r = Application.Evaluate("CHOOSE({1,2},A1:B5,E1:F5)")

    Dumper r

End Sub

Sub Dumper(arr)
Dim r, c, s, v
    For r = 1 To UBound(arr, 1)
        s = ""
        For c = 1 To UBound(arr, 2)
            v = arr(r, c)
            s = s & vbTab & IIf(IsError(v), "Err!", v)
        Next c
        Debug.Print s
    Next r
End Sub

Here's the output:
A1  F1
A2  F2
A3  F3
A4  F4
A5  F5

Is that what you'd expect ?

A: I would use range.formulaR1C1 property.
Table3AddressR1C1 = Workbooks("gangstar.xlsx").Worksheets("60 in August 2016-26082016-1137").Range("A1:A1000").address(,,xlR1C1, true)
Table2AddressR1C1 = Workbooks("gangstar.xlsx").Worksheets("60 in August 2016-26082016-1137").Range("H1:H1000").address(,,xlR1C1, true)

Sheet1.Range(Cells(1, Dept_Clm), Cells(Table1.rows.count, Dept_Clm)).FormulaR1C1 = "=VLookup(RxCx, Choose({1,2}, Table2AddressR1C1, Table3AddressR1C1), 2, False)"