text:
Q: Is routing API calls through my own RESTful API considered an acceptable strategy? This question might be considered opinionated but I really can't seem to find a straight answer. So either I'm missing something or I'm asking the wrong questions.
So, I'm an undergrad student and new in the whole Spring app development and I'm currently creating an app with React acting as the frontend and building a RESTful API using Spring in order to support it with necessary operations for the backend. Among other services, the backend API I'm building is used as a middle-man forwarding calls to the Google Geocoding API and other 3rd party APIs. **My biggest question since I started this is, is this a valid strategy? ** (at least, something acceptable by industry professionals)
My Research

*

*The biggest pro that this method has is that it allows me to effectively hide my API keys from the client rendering any attacks impossible.

*At the same time, this whole process adds (I believe) unnecessary complexity and delay in the overall responses resulting in a possible hindered user experience.

*Something I'm not quite sure yet would be that I'll have to add async capabilities to the services exposed by my own API in order to facilitate multiple users. (This last part might be entirely wrong but I haven't been able to understand how multiple users are handled when querying the same endpoint concurrently.)

*I have used Apache JMeter to test the performance of the app on concurrent POST calls and it seems to be able to handle them on around 170ms. (I'll post screenshots of the results below.)

Code
I'll try to include code demonstrating the controller that's responsible for the calls to the Geocoding API.
@RestController
@RequestMapping("/api")
@Slf4j
@RequiredArgsConstructor
@Component
public class GeocodingController {
    private final OkHttpClient httpClient = new OkHttpClient();

    @PostMapping(value = "/reversegeocoding")
    public String getReverseGeocode(@RequestBody LatLng latlng) throws IOException, ExecutionException, InterruptedException {
        String encodedLatLng = latlng.toString();
        Request request  = new Request.Builder()
                .url("https://maps.googleapis.com/maps/api/geocode/json?" +
                        "language=en&result_type=street_address&latlng=" + encodedLatLng +
                        "&key=MY_API_KEY")
                .build();

        CallbackFuture future = new CallbackFuture();
        httpClient.newCall(request).enqueue(future);
        Response response = future.get();
        return response.body().string();

    }
}

The getReverseGeocode() method takes in as an argument the following object:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LatLng {

    double lat;
    double lng;

    public String toString() {
        return lat + "," + lng;
    }
}

So, the Request Body is mapped onto the above object once the request arrives.
Finally the CallbackFuture is just an adapter class based on this answer.
public class CallbackFuture extends CompletableFuture<Response> implements Callback {

    @Override
    public void onFailure(Call call, IOException e) {
        super.completeExceptionally(e);
    }

    @Override
    public void onResponse(Call call, Response response) {
        super.complete(response);
    }
}

JMeter Results

A: Yeah, this is done all the time. Not all external APIs are setup to allow for you to grant access to your users directly.  You also may have requirements for logging and or access control. It does mean you need to dedicate your resources to the calls but unless you are expecting an excessive load its not worth optimizing for too far in advance.  Sometimes you can offload the proxy responsibilities to something like nginix instead which can be more efficient than your application backend.
In my experience it is worthwhile to keep these proxies in their own separate package that is isolated from your other code where possible. Then if you need to scale them independently of your main app you can easily break them out.

A: Yes, this is an entirely valid strategy.  There are many benefits to using this approach and whilst it can feel like it's adding unnecessary complexity, the benefits often out way the cost.
Firstly you're avoiding "leaky abstractions", the client shouldn't care how you implement a particular piece of functionality, they just care that it works!  It also means that you should be able to change the implementation in the future without the client even knowing.
Secondly, you're decoupling your APIs from others.  If the wrapped API changes, you can handle this yourself without the clients having to change their code (there will be times when this can't be done, but it offers a good defence to this).
Also, it gives you a convenient point to implement your own functionality around these APIs (rate limiting, access control and logging for example).
The @Async issue is not specific to wrapping third party APIs, it's an issue for all endpoints you have which have blocking IO.

A: It is common. Recently did this to a third party api adding Cross Origin headers so clients could perform cross origin requests. Also the original JSON was malformed in some cases so it was possible to cleanly handle that scenario.
The first is very easy with Spring boot and as you can just decorate the controller with @CrossOrigin(maxAge = 3600)


text:
Q: What conditions will the data type become KerasTensor?When I build a generator for CGAN I was learning CGAN based on mnist, when I try to build a generator,the type of model output is KearsTensor, which is different from the model output in case([https://github.com/eriklindernoren/Keras-GAN/blob/master/cgan/cgan.py]). I want to Convert KerasTensor to numpy array so that could be shown by matplotlib.
The difference bewteen the case and my model is that my label have ten features(float64).Is it because I'm not using the embedding layer correctly? Or is it because of my data input ? Is there have a better solution to merge the label and noise?
this is the code from case:
def build_generator(self):

        model = Sequential()

        model.add(Dense(256, input_dim=self.latent_dim))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(1024))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(np.prod(self.img_shape), activation='tanh'))
        model.add(Reshape(self.img_shape))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        label = Input(shape=(1,), dtype='int32')
        label_embedding = Flatten()(Embedding(self.num_classes, self.latent_dim)(label))

        model_input = multiply([noise, label_embedding])
        img = model(model_input)

        return Model([noise, label], img)

this is part of my code:
def build_generator():

    model = Sequential()

    model.add(Dense(256, input_dim=latent_dim))
    model.add(LeakyReLU(alpha=0.2))
    model.add(BatchNormalization(momentum=0.8))

    model.add(Dense(512))
    model.add(LeakyReLU(alpha=0.2))
    model.add(BatchNormalization(momentum=0.8))

    model.add(Dense(1024))
    model.add(LeakyReLU(alpha=0.2))
    model.add(BatchNormalization(momentum=0.8))

    model.add(Dense(1024))
    model.add(LeakyReLU(alpha=0.2))
    model.add(BatchNormalization(momentum=0.8))

    model.add(Dense(1801, activation='tanh'))
    model.add(Flatten())

    model.summary()

    noise = Input(shape=(100,))
    label = Input(shape=(10,))
    model_input = Input(shape=(100,))

    label_embedding = Flatten()(Embedding(1500, 10, input_length=10)(label)) # (None,100)

    model_input = multiply([noise, label_embedding]) # (None,100)

    time_history = model(model_input)

    return Model([noise, label], time_history)

generator = build_generator()
noise = np.random.normal(0, 1, (1, latent_dim))
label = y_train.iloc[0] # Series with shape (10,) and dtype float64
label = Input(shape=(label_dim,))

gen_historys = generator([noise, label])
print(gen_historys.shape) # (None,1801)
print(gen_historys[0].shape) # (1801,)
print(gen_historys) # KerasTensor(type_spec=TensorSpec(shape=(None, 1801), dtype=tf.float32, name=None), name='model_2/model_1/sequential_1/flatten/Reshape:0', description="created by layer 'model_2'")

I have tried some methods:
tf.keras.backend.get_value(gen_historys)

tf.config.run_functions_eagerly(True)

submodel = Model(model_input, time_history)
time_history = submodel.predict(model_input)

with tf.compat.v1.Session() as sess:
  print(sess.run(gen_historys))

but not worked, AttributeError: 'KerasTensor' object has no attribute 'numpy'
I do another test:
    input1 = tf.keras.layers.Input(shape=(16,))
    # x1 = tf.keras.layers.Dense(
    #     8, activation='relu')(input1) #shape=(None, 8)
    x1 = Flatten()(Embedding(1000, 2, input_length=16)(input1)) #(None, 32)

    input2 = tf.keras.layers.Input(shape=(32,))
    x2 = tf.keras.layers.Dense(
        32, activation='relu')(input2) #shape=(None, 32)
    out = tf.keras.layers.multiply([x1,x2]) #shape=(None, 32)
    out = tf.keras.layers.Dense(4, activation='tanh')(out)

    model = tf.keras.models.Model(inputs=[input1, input2], outputs=out)

    x11 = np.random.randint(0,1000,(1,16))
    x22 = np.random.normal(0,1,(1,32))
    y = model([x11,x22])
    print(y)

output: tf.Tensor([[-0.04395372 -0.0116075  -0.00716107  0.01199071]], shape=(1, 4), dtype=float32)
enter image description here
I want to know when the output result is eagertensor and when it is kerastensor.
Any help would be greatly appreciated!! Sincerely
I want to konw why the type of model output is KearsTensor rather than variable. And any advice on fusing labels and noise is greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get all connected IP´s on the Linux machine Recently i was asked a question in an interview which i couldn't do. Anyone got a solution for this?
Grab all connected IP´s on the Linux machine
check every connected IP if TCP port 1706 is open

if its open > execute command.  CURL 'http:// some address '
Else do nothing.
program will check this every 60 minits

Plattform Linux Ubuntu Server 12. X64 / x32

WAP in C++
Thanks!!

A: Make a bash script.
LOGIC:
Use netstat -natp (filter it through awk/sed to get the ports, then grep it) Then use a simple test to see if the result was empty. Run curl if it was.
Put this in a cron job. Simple stuff, really.
EDIT:
netstat is a utility which will show you all of the connections on your computer. netstat -natp shows a list of the programs which have tcp sockets on your computer.
sed and awk are used for text formatting. You can use them to list a specific column.
grep searches input to find a specified string.
bash allows for basic logic, and can be used to see if a string is empty.
cron is a linux process which schedules commands to be run at certain times.
EDIT #2:
You COULD poll /proc/net/tcp, but since netstat does that and formats it nicely, why bother?

A: In Linux, you look for files in /proc/net and parse that.
For example, TCP connections are listed in /proc/net/tcp
head /proc/net/tcp

will show something like this
  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
   0: 00000000:0007 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 38148735 1 0000000000000000 100 0 0 10 -1
   1: 00000000:1F48 00000000:0000 0A 00000000:00000000 00:00000000 00000000   116        0 38923158 1 0000000000000000 100 0 0 10 -1
   2: 00000000:0CEA 00000000:0000 0A 00000000:00000000 00:00000000 00000000   120        0 12364094 1 0000000000000000 100 0 0 10 -1
   3: 0100007F:13AD 00000000:0000 0A 00000000:00000000 00:00000000 00000000  1000        0 26454267 1 0000000000000000 100 0 0 10 -1
   4: 0100007F:008F 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 5570 1 0000000000000000 100 0 0 10 -1
   5: 00000000:0050 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 27328173 1 0000000000000000 100 0 0 10 -1
   6: 0100007F:1913 00000000:0000 0A 00000000:00000000 00:00000000 00000000   116        0 38923868 1 0000000000000000 100 0 0 10 -1
   7: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 18983193 1 0000000000000000 100 0 0 10 -1
   8: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 38681424 1 0000000000000000 100 0 0 10 -1

You can then split the lines, look for the open connections and act accordingly. Look at thesource of netstat for more.


text:
Q: can't insert values to a SQLite table I'm having hard time figuring out why im getting an error when I inserting values to the table.
thanks for the help.
Basically,the code worked when it only with two column and one             contentValues.put function but,when I added another column i keep getting error trying to inset values and i don't know why.
I have checked the SQlite query etc..
package com.avrahamzilberblat.battleshipfinal;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";
    private static final String TABLE_NAME = "people_table";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";
    private static final String COL3 = "scoreRatio";

    public DatabaseHelper(Context context) {

        super(context, TABLE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +COL2 +" TEXT,"+ COL3 +"INTEGER"+");";
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL2 +" TEXT,"+COL3+"TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean addData(String item,int scoreRatio) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item);
        contentValues.put(COL3, 5);

        long result = db.insert(TABLE_NAME, null, contentValues);

        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Returns all the data from database
     * @return
     */
    public Cursor getData(){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Returns only the ID that matches the name passed in
     * @param name
     * @return
     */
    public Cursor getItemID(String name,Double scoreRatio){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
                " WHERE " + COL2 + " = '" + name + "'" + " AND " +COL3 + " = '" + scoreRatio+"'";
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Updates the name field
     * @param newName
     * @param id
     * @param oldName
     */
    public void updateName(String newName, int id, String oldName){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
                " = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
                " AND " + COL2 + " = '" + oldName + "'";
        Log.d(TAG, "updateName: query: " + query);
        Log.d(TAG, "updateName: Setting name to " + newName);
        db.execSQL(query);
    }

    /**
     * Delete from database
     * @param id
     * @param name
     */
    public void deleteName(int id, String name){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + COL1 + " = '" + id + "'" +
                " AND " + COL2 + " = '" + name + "'";
        Log.d(TAG, "deleteName: query: " + query);
        Log.d(TAG, "deleteName: Deleting " + name + " from database.");
        db.execSQL(query);
    }
    public void clearDatabase(String TABLE_NAME) {
        SQLiteDatabase db = this.getWritableDatabase();
        String clearDBQuery = "DELETE FROM "+TABLE_NAME;
        db.execSQL(clearDBQuery);
    }

}

--------------------This is the update i want a string and a double data type,still doesn't work
@Override
public void onCreate(SQLiteDatabase db) {
    //String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +COL2 +" TEXT,"+ COL3 +"INTEGER"+");";
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL2 +" TEXT,"+COL3 +"REAL);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean addData(String item,int scoreRatio) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, "ood");
    contentValues.put(COL3, 6.6);

A: You should change :-
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL2 +" TEXT,"+COL3+"TEXT)");

to :-
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY, " +
            COL2 +" TEXT,"+COL3+" TEXT)");

Then you should do one of the following :-

*

*Delete(Clear) the App's data from settings/apps.

*uninstall the App.

*Increase the database version e.g. change super(context, TABLE_NAME, null, 1); to super(context, TABLE_NAME, null, 2);
and then rerun the App.
The above is important as onCreate only ever runs automatically once, when the database is created, which is perhaps the root cause of you issue. You've added a column but it actually hasn't been added.

I have played with it a lot i actually want it to be a real number
such as Double so in the beginning i wrote REAL instead of TEXT

SQlite allows any type of data to be stored in any type of column with one exception and that is an alias of the rowid (column defined with INTEGER PRIMARY KEY (with or without AUTOINCREMENT)). An alias of rowid can only store a integer (signed 64 bit) and it must be UNIQUE within the table.

*

*Note AUTOINCREMENT has been omitted. You very likely don't need it and it's got overheads

SQLite Autoincrement
Which includes :-

The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed.


text:
Q: Brace highlighting in Nano text editor? Is there a method for highlighting matched brace pairs in nano text editor?
My understanding is syntax can be changed in the config file, but unlike gedit there is no gui option to select brace highlighting.
Alternately, im more than happy to hear sugfestio s for a text editor thats linux compatible and semi-light weight.
*Needs to be compatible with c++.


text:
Q: add prebuilt jar to AOSP I am trying to add a prebuilt jar to Android when I compile AOSP.
The name of the jar is "nxpnfclib.jar" and I put it to AOSP/prebuilts/misc/common/nxp. I also write a Android.mk:
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_PREBUILT_JAVA_LIBRARIES := \
    nxpnfclib$(COMMON_JAVA_PACKAGE_SUFFIX)

LOCAL_MODULE_TAGS := optional

include $(BUILD_HOST_PREBUILT)

I want to use this jar in AOSP/packages/apps/Settings, so I add nxpnfclib to AOSP/packages/apps/Settings/Android.mk
LOCAL_STATIC_JAVA_LIBRARIES := guava android-support-v4 jsr305 nxpnfclib

However, when I compile the whole AOSP, some errors occur:

Warning: class [com/nxp/nfclib/ntag/╦К.class] unexpectedly contains
  class [com.nxp.nfclib.ntag.ˊ] Warning: there were 30 classes in
  incorrectly named files.
           You should make sure all file names correspond to their class names.
           The directory hierarchies must correspond to the package hierarchies.
           If you don't mind the mentioned classes not being written out,
           you could try your luck using the '-ignorewarnings' option. Error: Please correct the above warnings first. make: ***
  [out/target/common/obj/APPS/Settings_intermediates/proguard.classes.jar]
  Error 1

How can I fix this error? It may come from proguard.
Is there some other way to add the jar?

A: Create one more directory libs into src and place the jar file into it. Then add these few more lines to Android.mk file
LOCAL_STATIC_JAVA_LIBRARIES += nxpnfclib
include $(CLEAR_VARS)
LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES:=nxpnfclib:src/libs/nxpnfclib.jar
include $(BUILD_MULTI_PREBUILT)

A: To build prebuilt jar to AOSP pls using BUILD_PREBUILT in Android.mk like below
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := nxpnfclib
LOCAL_SRC_FILES := nxpnfclib.jar # path to your jar file
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE_CLASS := JAVA_LIBRARIES
LOCAL_MODULE_SUFFIX := $(COMMON_JAVA_PACKAGE_SUFFIX)
LOCAL_UNINSTALLABLE_MODULE := true
include $(BUILD_PREBUILT)

To use this library in AOSP/packages/apps/Settings, pls add nxpnfclib to LOCAL_STATIC_JAVA_LIBRARIES in Android.mk of Settings like this:
LOCAL_STATIC_JAVA_LIBRARIES += nxpnfclib


text:
Q: Python import no module found, but add "." works My folder struct:
/root/main.py
/root/subdir/__init__.py
/root/subdir/b.py
/root/subdir/c.py

/root/subdir/c.py:
def foo():
    pass

/root/subdir/b.py:
from c import foo
def func():
    pass

/root/main.py:
from subdir.b import func

python main will cause error:
No module named "c"

if I change /root/subdir/b.py to:
from .c import foo
def func():
    pass

it works properly.
Any one can explain the reason to cause the error?


text:
Q: Trying to upload images to Amazon S3 but getting error I am trying to upload images to Amazon S3 but keep getting this error: "VM222:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0". I am not sure what to do. I followed all of the example code from the website. And my code is written below.
const uploadFile = (file, signedRequest, url) => {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', signedRequest);
    xhr.onreadystatechange = () => {
      if(xhr.readyState === 4){
        if(xhr.status === 200){
          document.getElementById('preview').src = url;
          document.getElementById('avatar-url').value = url;
        }
        else{
          alert('Could not upload file.');
        }
      }
    };
    xhr.send(file);
  }

  const getSignedRequest = (file) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/sign-s3?file-name=${file.name}&file-type=${file.type}`);
    xhr.onreadystatechange = () => {
      if(xhr.readyState === 4){
        if(xhr.status === 200){
          const response = JSON.parse(xhr.responseText);
          uploadFile(file, response.signedRequest, response.url);
        }
        else{
          alert('Could not get signed URL.');
        }
      }
    };
    xhr.send();
  }

  const initUpload = () => {
    const files = document.getElementById('file-input').files;
    const file = files[0];
    if(file == null){
      return alert('No file selected.');
    }
    getSignedRequest(file);
  }

  return (

        <Title level={2}> Upload Prompt</Title>

      <Form onSubmit={onSubmit}>
        {/* DropZone */}
        {/* <FileUpload refreshFunction={updateImages} /> */}
        {/* kamran's code */}
        <input type="file" id="file-input" onChange={initUpload}/>

Any help is great appreciated. Thank you


text:
Q: Mac OS Creating PDF's weirdly large in size since I changed my iPhone I have recently bought an iPhone SE and switched to HEIC format for the pictures. I am sending the files to my Mac (Early 2015 Pro, Mojave) with AirDrop. Even though the sizes of images are just shy of 3 megabytes, the "Create PDF" function under "Quick Actions" is creating ~15MB per page PDFs which is kinda painful in quick upload situations. How can I resolve this enlargement issue of Preview creating PDFs?
Thank you beforehand!
Cheers,
~bio

A: The Create PDF Quick Action (or similar Automator actions) don't have any 'controls' for the way the PDF is created, (of the kind you find in Acrobat or the PDF Export dialog of some apps). It just 'wraps' the image data in a PDF format. (I think it may also stick the image on your default printer page size.)
It's possible that the HEIC format, being newer, contains compression that the PDF format can't use, so it has to use a less efficient method. How large (pixels) are the images?
It's certainly possible to resample the image data, or increase the compression used, of a PDF: you could create a new Quick Action to create the PDF and then downsample or compress it.
What's the purpose of converting them to PDF? Are you collating images together into one file?
There are other (dare I say better) Quick Actions for PDF manipulation, including one to Create a PDF from images, which is faster than Apple's own and preserves the images' dimensions.
https://github.com/benwiggy/PDFsuite

A: A PDF file usually stores an image as a separate object (an XObject) which contains the raw binary data for the image.
This is not generally an image in the sense of a TIFF or a JPEG – it is the binary data for the pixels, the colorspace used for the image and additional information.
The actual pixel data can be compressed and one of the compression formats (DCTDecode) is the same used as in a JPEG. If you save this data, it can be opened as a JPEG file, but it may need altering to include the colorspace data.
Depending on the tool used to create the PDF your HEIC file is "converted" and included in the PDF generated.
And depending on the parameters used when creating said PDF no compression might be used - besides the obvious, that is that HEIC is much more efficient for file size than the compression algorithms currently supported by Adobe's PDF (assuming you want to keep the pixel dimensions and dpi of you original images when included). So you might end up with a large file size for your PDF.
PDF is not a good image storage format. Why not use JPEG, TIFF or PNG?
EDIT: if you have a folder of HEIC files on your Mac, launch the terminal (Zsh) and create JPEG copies of your HEIC using sips:
for i in *.heic(:r) ; sips -s format jpeg "$i.heic" --out "$i.jpg"


text:
Q: ClientRpc Function not being carried out on all clients in Unity3d c# Currently I am working on a networked 2d platformer game. I have a script that is supposed to instantiate the players jetpack called JetpackManager. However when the player is spawned into the scene the code only spawns a jetpack into the hosts scene and not into the clients' scenes. This results in only the hosts scene working properly while all the players in the clients' scenes have no jetpacks. This is my code for the JetpackManager:
using UnityEngine;
using UnityEngine.Networking;

public class JetpackManager : NetworkBehaviour {

[SerializeField]
private Jetpack[] jetpacks;

[SerializeField]
private Transform jetPackHold;

private PlayerController playerController;

private Jetpack currentJetpack;

void Start(){
    playerController = GetComponent<PlayerController> ();

    if (isLocalPlayer) {
        CmdEquipJetpack (0);
    }
}

[Command]
void CmdEquipJetpack(int jetpackNumber){
    RpcEquipJetpack (jetpackNumber);
}

[ClientRpc]
void RpcEquipJetpack(int jetpackNumber){

    if (currentJetpack != null) {
        Destroy (currentJetpack.gameObject);
    }

    currentJetpack = Instantiate (jetpacks[jetpackNumber], jetPackHold.position, jetPackHold.rotation);
    currentJetpack.transform.SetParent (jetPackHold);

    playerController.InitialiseJetpackVariables (currentJetpack);
}

}
So essentially my problem is that the code within the RpcEquipJetpack Function is for some reason only being called on the host and not on any of the clients.

A: You should instantiate Network object with network class
Network.Instantiate

Network instantiate a prefab.
The given prefab will be instanted on all clients in the game.
  Synchronization is automatically set up so there is no extra work
  involved. The position, rotation and network group number are given as
  parameters. Note that in the example below there must be something set
  to the playerPrefab in the Editor. You can read more about
  instantiations in the object reference Object.Instantiate.


text:
Q: How to prove that $\sum_{n=1}^{\infty}\frac{u_n}{n}$ diverges?
Let $u_n>u_{n+1}>0$ for all $n \in \Bbb N$, and suppose that $u_2+u_4+u_8+u_{16}+\dots$ diverges. Prove that $\sum_{n=1}^{\infty}\frac{u_n}{n}$diverges.

Please provide me a hint or a full solution.

A: I suggest that you read about the Cauchy condensation test.

A: Hint: think about the partial sums
$$ S_k = \sum_{n = 2^k+1}^{2^{k+1}} \frac{u_n}n$$
Notice that $$\sum_{n=1}^\infty \frac{u_n}n = u_1 + \frac{u_2}2 + \sum_{k=1}^\infty S_k$$
so it's enough to show that the sequence $\sum_{k=1}^\infty S_k$ diverges.
Notice that the terms in the partial sums $S_k$ are decreasing.  Therefore the smallest term in the sum is the last one, $\frac{u_{2^{k+1}}}{2^{k+1}}$.
As there are $2^k$ terms in each sum we must have
$$\sum_{n = 2^k+1}^{2^{k+1}} \frac{u_n}n \geq 2^{k} \frac{u_{2^{k+1}}}{2^{k+1}}=\frac{u_{2^{k+1}}}{2} $$
So $$\sum_{n=1}^\infty \frac{u_n}n \geq u_1 + \frac 12\left(u_2 + u_4 + u_8 + \dots\right)$$which we are given as divergent.

A: $\sum_{n=2^m}^{2^{m+1}-1}\frac{u_n}{n}
>\sum_{n=2^m}^{2^{m+1}-1}\frac{u_{2^{m+1}}}{2^{m+1}}
= 2^m \frac{u_{2^{m+1}}}{2^{m+1}}
=u_{2^{m+1}}/2
$.
Therefore
$\sum_{n=1}^{2^m-1} \frac{u_n}{n}
> \frac1{2}\sum_{k=1}^m u_{2^k}
$
and, if the latter sum diverges, so does the former.
Note that an almost identical argument will show that
if $(a_m)_{m=1}^{\infty}$
is an increasing sequence of positive integers
such that there is a $c < 1$ such that
$\frac{a_{m}}{a_{m+1}} \le c$ for all $m$,
and $u_n \ge u_{n+1}$ for all $n$,
then $\sum_{m=1}^{\infty} u_{a_m}$ diverges
implies that
$\sum_{n=1}^{\infty} \frac{u_n}{n}$ diverges.
Here is the proof by copy and paste:
$\sum_{n=a_m}^{a_{m+1}-1}\frac{u_n}{n}
>\sum_{n=a_m}^{a_{m+1}-1}\frac{u_{a_{m+1}}}{a_{m+1}}
= (a_{m+1}-a_m) \frac{u_{a_{m+1}}}{a_{m+1}}
=(1-\frac{a_{m}}{a_{m+1}})u_{a_{m+1}}
=(1-c)u_{a_{m+1}}
$.
Therefore
$\sum_{n=1}^{a_m-1} \frac{u_n}{n}
> (1-c)\sum_{k=1}^m u_{a_k}
$
and, if the latter sum diverges, so does the former.
The fact that $1-\frac{a_{m}}{a_{m+1}}$
occurs leads to the requirement on $a_m$.
We can also go the other way
and see what is needed.
$\sum_{n=a_m}^{a_{m+1}-1}\frac{u_n}{n}
<\sum_{n=a_m}^{a_{m+1}-1}\frac{u_{a_{m}}}{a_{m}}
= (a_{m+1}-a_m) \frac{u_{a_{m}}}{a_m}
=(\frac{a_{m+1}}{a_m}-1)u_{a_{m}}
$.
From this we see that if
$\frac{a_{m+1}}{a_m}-1 < d$
for some real $d$ and all $m$,
then
$u_{a_{m}} > \frac1{d}\sum_{n=a_m}^{a_{m+1}-1}\frac{u_n}{n}$,
so that
$\sum \frac{u_n}{n}$ diverges
implies that
$\sum u_{a_m}$ diverges.
Combining these two,
we get this:
If $(a_m)_{m=1}^{\infty}$
is an increasing sequence of positive integers
such that there exists positive reals $c$ and $d$ such that
$c \le \frac{a_{m+1}}{a_{m}}-1 \le d$ for all $m$,
and $u_n \ge u_{n+1}$ for all $n$,
then $\sum_{m=1}^{\infty} u_{a_m}$ converges
if and only if
$\sum_{n=1}^{\infty} \frac{u_n}{n}$ converges.

A: Suppose $ u_n = (\log n)^{-1}$


text:
Q: Insert rows from another table, based on a select from a third table I have a SELECT statement:
SELECT searchstring1, searchstring2 FROM t1 WHERE user_id = number;

Which produces multiple rows:
[result1, result2]
[result3, result4]
[result5, result6]

Now I want to use these rows for a new SELECT statement, like this:
SELECT val1, val2, val3 FROM t2 WHERE val1 LIKE '%searchstring1%' AND val2 = 'searchstring2';

Which produces even more rows:
[result7, result8, result9]
[result10, result11, result12]
.
.
.
[result100, result101, result102]

And then insert the resulting rows into a third table:
INSERT INTO t3 (val1, val2, val3) VALUES ('result7', 'result8, 'result9');
INSERT INTO t3 (val1, val2, val3) VALUES ('result10', 'result11, 'result12');
.
.
.

I know I have to do some form of join on the first two, and probably have to do the insert as a new query - but I have no idea how to do it. Can you help? And is it possible to do all this in one query?

A: Maybe something like this:
INSERT INTO t3 (val1, val2, val3)
SELECT
    t2.val1,
    t2.val2,
    t2.val3
FROM
    t2
WHERE EXISTS
    (
        SELECT
            NULL
        FROM
            t1
        WHERE
            t2.val1 LIKE CONCAT('%',t1.searchstring1,'%')
            AND t2.val2 LIKE CONCAT('%',t1.searchstring2,'%')
            AND t1.user_id = number
    )


text:
Q: Generic type params not inferred when argument is a function In this code I have here:
type GETR<a extends string, b extends string> = [a,b]

interface Options<A extends string, B extends string> {
  bar: GETR<A,B>
}

function foo<A extends string, B extends string, C extends Options<A, B>>(r: C) {
  return r
}

const bar:GETR<"foo", "bar"> = null as any as GETR<"foo", "bar">

const x = foo({ bar })

There are no type errors. See it here
Now if all I change is the type of GETR from [a,b] to (k:a) => b with no other changes. Then the generic type params no longer get inferred and I have a type error:
type GETR<a extends string, b extends string> = (k:a) => b

interface Options<A extends string, B extends string> {
  bar: GETR<A,B>
}

function foo<A extends string, B extends string, C extends Options<A, B>>(r: C) {
  return r
}

const bar:GETR<"foo", "bar"> = null as any as GETR<"foo", "bar">

const x = foo({ bar })

Has a type error. See it here
I am trying to understand why, and what the best fix is?

A: I believe this is because contravariance. However, I am not 100% sure, because it also might be invariance.
There is an easy fix, just get rid of C generic argument:
type Fn<Arg extends string, Return extends string> = (k: Arg) => Return

interface Options<Arg extends string, Return extends string> {
  prop: Fn<Arg, Return>
}

function foo<
  Arg extends string,
  Return extends string,
>(r: Options<Arg, Return>) {
  return r
}

declare const prop: Fn<"foo", "bar">

const x = foo({ prop }) // ok

Playground
Consider this small example:
declare let stringString: Options<string, string>
declare let fooBar: Options<'foo', 'bar'>

stringString = fooBar // error
fooBar = stringString // error

As you might have noticed: stringString and fooBar are not assignable to each other.
The problem is in Arg generic type (in your example it is a). If you get rid of Arg (a), your example will compile:
type Fn<Return extends string> = () => Return

type Options<Return extends string> = {
  prop: Fn<Return>
}

function foo<
  Return extends string,
  C extends Options<Return>
>(r: C) {
  return r
}

declare const prop: Fn<"bar">

const x = foo({ prop }) // no error

It compiles, because Return is in covariant position.
Let's try to add back Arg but get rid of Return:
type Fn<Arg extends string> = (arg: Arg) => void

type Options<Arg extends string> = {
  prop: Fn<Arg>
}

function foo<
  Arg extends string,
  C extends Options<Arg>
>(r: C) {
  return r
}

declare const prop: Fn<"foo">

const x = foo({ prop }) // still error

declare let stringPrimitive: string;
declare let fooBarPrimitive: 'bar'

stringPrimitive = fooBarPrimitive // ok
fooBarPrimitive = stringPrimitive  // error

declare let stringString: Options<string>
declare let fooBar: Options<'bar'>

stringString = fooBar // error
fooBar = stringString // ok

Playground
There is still an error. Please check assignability of stringPrimitive , fooBarPrimitive, stringString and fooBar.
In first example, fooBarPrimitive literal type is assignable to string and it is expected. However, in second example, fooBar is no more assignable to stringString because of contravariance. Function arguments are in contravariant positions.
Let's try to add Return generic (in your example it is b):
type Fn<Arg extends string, Return extends string> = (arg: Arg) => Return

type Options<Arg extends string, Return extends string> = {
  prop: Fn<Arg, Return>
}

function foo<
  Arg extends string,
  Return extends string,
  C extends Options<Arg, Return>
>(r: C) {
  return r
}

declare const prop: Fn<"foo", 'bar'>

const x = foo({ prop }) // still error

declare let stringString: Options<string, string>
declare let fooBar: Options<'foo', 'bar'>

stringString = fooBar // error
fooBar = stringString // error

Playground
Please check assignability of stringString and fooBar, they are no more assignable to each other at all. In both cases you have got an error.
From what I understood, adding C generic triggers contravariant behavior of Arg generic.
This is not the first time I have faced such behavior.
Consider this example, but please turn off strictFunctionTypes flag:
type Animal = { tag: 'animal' }

type Dog = Animal & { bark: true }
type Cat = Animal & { meow: true }

declare let animal: (x: Animal) => void;
declare let dog: (x: Dog) => void;
declare let cat: (x: Cat) => void;

animal = dog; // ok without strictFunctionTypes and error with

dog = animal; // should be ok

dog = cat; // should be error

dog is assignable to animal but should not be.
Now, try add generic to animal function:
type Animal = { tag: 'animal' }
type Dog = Animal & { bark: true }

// generic is here
declare let animal: <T extends Animal>(x: T) => void;
declare let dog: (x: Dog) => void;

animal = dog; // error even without strictFunctionTypes

Now, dog is not assignable to animal even without strictFunctionTypes flag. I did not find an explanation of this behavior in docs.
See corresponding article here
Please check this answer if you are interested in *-variance topic.
P.S. I will be happy if somebody will confirm or critic my thoughts, I was trying my best


text:
Q: ESXi Not Booting from USB I hope you can help, because I'm stumped.
I've got an old HP DL385 G2 server. I have successfully installed VMWare ESXi 6.0 to an old 16GB Corsair Voyager flash drive.
Because I didn't like the USB hanging off the server, I figured I'd utilise the internal port, and would get a physically smaller USB drive to do so.
As such, I got myself a 16GB Sandisk Cruzer Fit. I went through the exact same install process as before. The install completes successfully. Upon reboot however, I get an error
SYSLINUX 3.86 EBIOS load error

I did some research, and found that it may be as a result of the USB not working so well with GPT partitioning. So, as per the recommendations found whilst researching, I booted the installer with the boot option 'formatwithmbr' so as to use MBR rather than GPT partitioning. Again, the installer completes successfully, but I'm greeted with the same wonderful error.
I'm about ready to toss the drive - is there anything else that somebody may suggest?
EDIT: I have tested the Corsair Voyager on the internal port which works successfully, and the Cruzer will not work on either.

A: have you compared the USB disk identifier on both to see WHICH FAT32 or NTFS each version is using?  this is often a drive format error - there are a about 20 different FAT32 formats , and quite a few NTFS - GRUB has problems with some of them


text:
Q: AWS Lambda NodeJS - OAuth to Google API I'm using my own gmail user to read a public calendar. Got program working locally, and displayed the credentials/token with console.log (value altered to protect my token):
Got Token
OAuth2Client {
  transporter: DefaultTransporter {},
  _certificateCache: null,
  _certificateExpiry: null,
  _clientId: 'xxxxxxxxxxxxxx',
  _clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  _redirectUri: 'urn:ietf:wg:oauth:2.0:oob',
  _opts: {},
  credentials:
   { access_token: 'xxxxxxx',
     refresh_token: 'xxxxxxxxxxxxxxxxxx',
     token_type: 'Bearer',
     expiry_date: 1512151860704 } }

I also did what StackOverflow said: How to oAuth Google API from Lambda AWS? and it gave me the same access_token as displayed above.
So, if I understand, I need to take the access token and put it in my program or a file, and I'm not sure how to do that.  My code came from the Google example here:  https://developers.google.com/google-apps/calendar/quickstart/nodejs
Do I put this token somewhere in my client_secret.json file or what? I tried just passing it straight to the listEvents method as the value of TOKEN but got "400 Bad Request".
Update 1:
 I tried storing the file to disk and then reading it as follows:
exports.getCalendarJSONEventsNew =
  function getCalendarJSONEvents(callback) {
    console.log("started getCalendarJSONEventsNew");
    fs.readFile('OAuth2Client.json', 'utf8',
      function processedFile(err, content) {
          if (err) {
            console.log('Error loading OAuth2Client.json: ' + err);
            return;
          }

          console.log("content=");
          console.log(content);
          var tokenFromFile = JSON.parse(content);
          listEvents(tokenFromFile, function(jsonResult) {
                      console.log("Json Callback Events=");
                      console.log(jsonResult);
                      callback(jsonResult);
          });
    });

}

Error: It doesn't seem to be exactly be JSON, so not how to deserialize it back into object:
OAuth2Client {
^

SyntaxError: Unexpected token O in JSON at position 0

Update 2: Then I had another idea, I saved the following as
credentials: {
    access_token: 'xxxxx',
    refresh_token: 'xxxxxx',
    token_type: 'Bearer',
    expiry_date: 1512151860704
}

as .credentials/calendar-nodejs-quickstart.json.
Then when I ran on the server, I got this response back:
Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/auth?etc...

A: Here's how I got it to work so far.
1) Created a file called calendar-nodejs-quickstart.json in the root directory.
I kept getting errors when trying to read .credentials/calendar-nodejs-quickstart.json.  I tried setting the environment variables, but ended up changing sample code as follows:
var TOKEN_DIR = '.credentials/';
var TOKEN_PATH = 'calendar-nodejs-quickstart.json';

2) Had to remove "credentials :" from the beginning of the file, and add the double quotes (and also changed single quotes to double quotes).  This was to get past various JSON parsing errors.
{
    "access_token": "xxxxx",
    "refresh_token": "xxxx",
    "token_type": "Bearer",
    "expiry_date": 1512151860704
}
3) I also added the 'utf8' below, and added some debug code to see what was going on:
  // Check if we have previously stored a token.
  console.log("TOKEN_PATH=" + TOKEN_PATH);
  fs.readFile(TOKEN_PATH, 'utf8', function(err, token) {
    if (err) {
      console.log("err=" + err);
      getNewToken(oauth2Client, callback);
    } else {
      console.log("Use stored tokens from " + TOKEN_PATH);
      console.log(token);
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });

Seems critical to me to show the value of the "err" variable.


text:
Q: Ruby on Rails - Settting up Reviews functionality I am trying to set up a feature on my Ruby on Rails app that lets users to review pictures.
I've followed this guide as a reference.
http://ruby.about.com/od/rubyonrails/ss/blogpart4_4.htm
From my experiences working on other Ruby on Rails projects, I think a Posts/Comments relationship model can be used here for a Pictures/Reviews relationship.
I first generated a scaffold.
rails g scaffold review name:string body:text picture:references

I would like each picture page to have a separate page for its own reviews.
Since I don't need an Index Page for my reviews controller, I removed this line from my routes.rb file
resources: reviews

I replaced that by creating routes
match '/pictures/:id/reviews', to: 'reviews#show', via: 'get'
match '/pictures/:id/reviews/edit', to: 'reviews#edit', via: 'get'
match '/pictures/:id/reviews/new', to: 'reviews#new', via: 'get'

Here, my path involves nesting reviews inside pictures.
Route
favorite_picture_path   PUT     /pictures/:id/favorite(.:format)    pictures#favorite
pictures_path           GET     /pictures(.:format)                 pictures#index
                        POST    /pictures(.:format)                 pictures#create
new_picture_path        GET     /pictures/new(.:format)             pictures#new
edit_picture_path       GET     /pictures/:id/edit(.:format)        pictures#edit
picture_path            GET     /pictures/:id(.:format)             pictures#show
                        PATCH   /pictures/:id(.:format)             pictures#update
                        PUT     /pictures/:id(.:format)             pictures#update
                        DELETE  /pictures/:id(.:format)             pictures#destroy
users_path              GET     /users(.:format)                    users#index
                        POST    /users(.:format)                    users#create
new_user_path           GET     /users/new(.:format)                users#new
edit_user_path          GET     /users/:id/edit(.:format)           users#edit
user_path               GET     /users/:id(.:format)                users#show
                        PATCH   /users/:id(.:format)                users#update
                        PUT     /users/:id(.:format)                users#update
                        DELETE  /users/:id(.:format)                users#destroy
sessions_path           POST    /sessions(.:format)                 sessions#create
new_session_path        GET     /sessions/new(.:format)             sessions#new
session_path            DELETE  /sessions/:id(.:format)             sessions#destroy
contacts_path           POST    /contacts(.:format)                 contacts#create
new_contact_path        GET     /contacts/new(.:format)             contacts#new
root_path               GET     /                                   pictures#welcome
users_new_path          GET     /users/new(.:format)                users#new
about_path              GET     /about(.:format)                    pictures#about
                        GET     /contacts(.:format)                 contacts#new
                        GET     /users/:id/favorites(.:format)      users#favorites
signup_path             GET     /signup(.:format)                   users#new
signin_path             GET     /signin(.:format)                   sessions#new
signout_path            DELETE  /signout(.:format)                  sessions#destroy
                        GET     /pictures/:id/reviews(.:format)     reviews#show
                        GET     /pictures/:id/reviews/edit(.:format)    reviews#edit
                        GET     /pictures/:id/reviews/new(.:format) reviews#new
updated_path            GET     /updated(.:format)              pictures#newest_updates
                        GET     /top-rated(.:format)            pictures#high_ratings

ReviewsController
class ReviewsController < ApplicationController
  before_action :set_review, only: [:show, :edit, :update, :destroy]

  def show
    @picture = Picture.find(params[:id])
    @review = Review.find(params[:id])
  end

  def new
    @review = Review.new
  end

  def edit
     @picture = Picture.find(params[:picture_id])
     @review = Review.find(params[:id])
  end

  def create
    @picture = Picture.find(params[:picture_id])
    @review = @picture.reviews.build(params[:review])

    if @review.save
      ;flash[:notice] = 'Review was successfully created.'
      redirect_to @picture
    else
      flash[:notice] = "Error creating review: #{@review.errors}"
      redirect_to @picture
    end
  end

  def update
    @picture = Picture.find(params[:picture_id])
    @review = Review.find(params[:id])

    if @review.update_attributes(params[:review])
      flash[:notice] = "Review updated"
      redirect_to @picture
    else
      flash[:error] = "There was an error updating your review"
      redirect_to @picture
    end
  end

  def destroy
    @picture = Picture.find(params[:picture_id])
    @review = Review.find(params[:id])
    @review.destroy
    redirect_to(@review.post)
  end

  private

    def set_review
      @review = Review.find(params[:id])
    end

    def review_params
      params.require(:review).permit(:username, :body, :picture_id)
    end
end

I deleted the index action from my ReviewsController.
Models
class Review < ActiveRecord::Base
  belongs_to :picture
end

class Picture < ActiveRecord::Base
  has_many :reviews
end

Above, I established a one-to-many relationship between pictures and reviews.
Reviews Migration
class CreateReviews < ActiveRecord::Migration
  def change
    create_table :reviews do |t|
      t.string :username
      t.text :body
      t.references :picture, index: true

      t.timestamps
    end
  end
end

Based on my understanding on Rails, this should work.
Pictures#Show Page
<% @title = "#{@picture.title}" %>

Picture Statistics

Title: <%= @picture.title %>

Category: <%= @picture.category %>

Rating: <%= pluralize(@picture.rating, 'Star') %>

Favorited: By <%= pluralize(@picture.users.count, 'User') %>

  <% if @picture.rating > 4 %>

  <button class = 'top-picture'>Top Rated</button>

  <% end %>

<%= form_for @picture do |f| %>

    <%= f.label :stars, 'Rating', class: 'indent' %>

      1 ☆<%= f.radio_button :stars, '1' %>
      2 ☆<%= f.radio_button :stars, '2' %>
      3 ☆<%= f.radio_button :stars, '3' %>
      4 ☆<%= f.radio_button :stars, '4' %>
      5 ☆<%= f.radio_button :stars, '5' %>

   <input class="btn btn-info" type="submit" value="Review">

  Reviews

<% end %>

  Index

However, when I click on a link in my Pictures/:id(show page)
Reviews

RecordNotFound Error
Active Record::RecordNotFound in ReviewsController#show
Couldn't find Review with id=:id

Extracted source (around line #54):
53 def set_review
54  @review = Review.find(params[:id])
55 end
56
57 def review_params

Since I encountered a RecordNotFound error, I suspect the problem lies in the ReviewsController, most likely with the params.
I believe that I have the right idea, but I made a mistake somewhere. Feedback and criticism are greatly appreciated. Sorry if this sounds like a stupid question, I'm just not very good in Ruby.

A: match '/pictures/:id/reviews', to: 'reviews#show', via: 'get'
match '/pictures/:id/reviews/edit', to: 'reviews#edit', via: 'get'

These 2 routes do not have a review id, but your controller action expects them. make this change
match '/pictures/:picture_id/reviews/:id', to: 'reviews#show', via: 'get'
match '/pictures/:picture_id/reviews/:id/edit', to: 'reviews#edit', via: 'get'

And change this
Reviews

to
Reviews

But you should seriously consider using Resourceful routes and helpers

A: As you have .html.erb file, try to avoid writing raw HTML.
Just update this link:
Reviews

To
<%= link_to "Reviews", picture_reviews_path(@picture) %>

Edit:
You should assign names to your match statements like:
match '/pictures/:id/reviews', to: 'reviews#show', via: 'get', :as => 'picture_reviews'

It will generate:
picture_reviews GET    /pictures/:id/reviews(.:format)          reviews#show

A: Routes
For the sake of posterity, you'll be best setting your routes up as follows:
#config/routes.rb
resources :pictures do
   resources :reviews, only: [:show, :edit, :new]
end

Whenever you create routes in Rails, you need to remember the entire framework has been built around "objects" / "resources". That's why the routes are known as resourceful routes (and why they have the resources directive) - they allow you to define the routes around the different resources of your application
I've recommend using a nested resources structure.
--
Helpers
Your problem was resolved using the code provided by Santosh and the like. IE:
<%= link_to "Your Link", your_link_path(@object) %>

You need to appreciate how this works. Each time you use a route helper in Rails (in the link_to helper), it will look through your routes & find the details it needs.
You were referencing the following path: pictures/:id/reviews - as discovered, this is wrong because Rails does not have any bearing on the URL of a link besides building it at render time.
Considering Rails is a stateless HTTP-based framework, Rails has to collate any data upon each request. This means if you want to build links, you have to let Rails build the link at render, passing a static set of data through to your controller in the back-end
Hopefully this helps?

A: Consider using nested resources rather than building them out manually
resources :pictures, except: [:index] do
  resources :reviews
end

And as others mentioned, you should use the rails link_to to generate proper URLs


text:
Q: best practise to do many connections mysqli I received  max_user_connections error this days. and I was wondering if I am doing something wrong.
I have a config.php file with mysqli connection script:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

so pages where I need to get something in mysqli I include config.php. here is an example:
example.php
<?php
     include_once("config.php");

     $stmt = $mysqli->prepare("select...");
     $stmt->execute();
     $stmt->bind_result(...,...);
     while($stmt->fetch()) {
         ...
     }
     $stmt->close();
?>

some html <p> <img>...

<?php
     $stmt = $mysqli->prepare("select...");
     $stmt->execute();
     $stmt->bind_result(...,...);
     while($stmt->fetch()) {
       ...
     }
     $stmt->close();
?>

some html <p> <img>...

<?php
      $stmt = $mysqli->prepare("select...");
      $stmt->execute();
      $stmt->bind_result(...,...);
      while($stmt->fetch()) {
        ...
      }
      $stmt->close();
?>

So, my question is: is it the best practise to do selects like this? should I close mysqli connect after each select and open again? or do selects on the top together without separete than with some html in the middle?

A:
the best practise to do selects like this?

I hate it when people use the term "best practice" it's usually a good indicator they don't know what they are talking about.
The advantage of your approach is that its nice and simple. But as you've discovered, it does not scale well.
In practice its quite hard to measure, but in most applications the MySQL connection is unused for most of the lifecycle of the script. Hence there are usually big wins to be made by delaying the opening of connection and closing it as soon as possible.
The former can be done by decorating the mysqli class, the connect method just stores the credentials while anything which needs to talk to the database should call the wrapped connect method when it needs access to the database. However typically the yeild of this approach is low unless your code creates a lot of database connections which are never used (in which case a cheaper solution would be to increase the connection limit).
It can take a long time after the last query is run before the connection is closed down. Explicitly closing the connection addresses this, but requires a lot of code changes.
do not open and close a connection for each query. Although it will result in a reduced number of connections to the databasee, the performance will suck
The biggest win usually comes from optimizing your queries - reduced concurrency and a better user experience.


text:
Q: query single table instead of all relational tables when using JPA We need to query user by userid to execute every web request to make sure the user exist. Every time it queries, it joins with other relational tables. How to avoid it? I just want to query only user table. I set the Fetz Type lazy for attachment table, but it still joins the attachment table. What i'm missing?
Log
Hibernate: select user0_.id as id1_6_, user0_.time_created as time_cre2_6_, user0_.uuid as uuid3_6_, user0_.version as version4_6_, user0_.email_address as email_ad5_6_, user0_.first_name as first_na6_6_, user0_.hashed_password as hashed_p7_6_, user0_.is_verified as is_verif8_6_, user0_.last_name as last_nam9_6_, user0_.photo_id as photo_i10_6_, user0_.public_id as public_11_6_, user0_.role as role12_6_, user0_.user_status as user_st13_6_ from user user0_ where user0_.email_address=?
Hibernate: select socialuser0_.user_id as user_id15_6_1_, socialuser0_.id as id1_5_1_, socialuser0_.id as id1_5_0_, socialuser0_.time_created as time_cre2_5_0_, socialuser0_.uuid as uuid3_5_0_, socialuser0_.version as version4_5_0_, socialuser0_.access_token as access_t5_5_0_, socialuser0_.display_name as display_6_5_0_, socialuser0_.expire_time as expire_t7_5_0_, socialuser0_.image_url as image_ur8_5_0_, socialuser0_.profile_url as profile_9_5_0_, socialuser0_.provider_id as provide10_5_0_, socialuser0_.provider_user_id as provide11_5_0_, socialuser0_.rank as rank12_5_0_, socialuser0_.refresh_token as refresh13_5_0_, socialuser0_.secret as secret14_5_0_, socialuser0_.user_id as user_id15_5_0_ from social_user socialuser0_ where socialuser0_.user_id=?
Hibernate: select sessions0_.user_id as user_id6_6_1_, sessions0_.id as id1_4_1_, sessions0_.id as id1_4_0_, sessions0_.is_keep_logged_in as is_keep_2_4_0_, sessions0_.last_updated as last_upd3_4_0_, sessions0_.time_created as time_cre4_4_0_, sessions0_.token as token5_4_0_, sessions0_.user_id as user_id6_4_0_ from session_token sessions0_ where sessions0_.user_id=?
Hibernate: select user0_.id as id1_6_1_, user0_.time_created as time_cre2_6_1_, user0_.uuid as uuid3_6_1_, user0_.version as version4_6_1_, user0_.email_address as email_ad5_6_1_, user0_.first_name as first_na6_6_1_, user0_.hashed_password as hashed_p7_6_1_, user0_.is_verified as is_verif8_6_1_, user0_.last_name as last_nam9_6_1_, user0_.photo_id as photo_i10_6_1_, user0_.public_id as public_11_6_1_, user0_.role as role12_6_1_, user0_.user_status as user_st13_6_1_, attachment1_.user_id as user_id18_6_3_, attachment1_.id as id1_0_3_, attachment1_.id as id1_0_0_, attachment1_.time_created as time_cre2_0_0_, attachment1_.uuid as uuid3_0_0_, attachment1_.version as version4_0_0_, attachment1_.attachment_date as attachme5_0_0_, attachment1_.attachment_size as attachme6_0_0_, attachment1_.attachment_type as attachme7_0_0_, attachment1_.attachment_url as attachme8_0_0_, attachment1_.file_id as file_id9_0_0_, attachment1_.images_generated as images_10_0_0_, attachment1_.mime_type as mime_ty11_0_0_, attachment1_.playback_formats as playbac12_0_0_, attachment1_.ready_for_playback as ready_f13_0_0_, attachment1_.secured as secured14_0_0_, attachment1_.title as title15_0_0_, attachment1_.total_pages as total_p16_0_0_, attachment1_.user_id as user_id18_0_0_, attachment1_.virus_status as virus_s17_0_0_ from user user0_ left outer join attachment attachment1_ on user0_.id=attachment1_.user_id where user0_.id=?
Hibernate: select pages0_.attachment as attachme1_0_3_, pages0_.pages as pages2_2_3_, attachment1_.id as id1_1_0_, attachment1_.attachment_id as attachme6_1_0_, attachment1_.file_id as file_id2_1_0_, attachment1_.mime_type as mime_typ3_1_0_, attachment1_.page_number as page_num4_1_0_, attachment1_.page_type as page_typ5_1_0_, attachment2_.id as id1_0_1_, attachment2_.time_created as time_cre2_0_1_, attachment2_.uuid as uuid3_0_1_, attachment2_.version as version4_0_1_, attachment2_.attachment_date as attachme5_0_1_, attachment2_.attachment_size as attachme6_0_1_, attachment2_.attachment_type as attachme7_0_1_, attachment2_.attachment_url as attachme8_0_1_, attachment2_.file_id as file_id9_0_1_, attachment2_.images_generated as images_10_0_1_, attachment2_.mime_type as mime_ty11_0_1_, attachment2_.playback_formats as playbac12_0_1_, attachment2_.ready_for_playback as ready_f13_0_1_, attachment2_.secured as secured14_0_1_, attachment2_.title as title15_0_1_, attachment2_.total_pages as total_p16_0_1_, attachment2_.user_id as user_id18_0_1_, attachment2_.virus_status as virus_s17_0_1_, user3_.id as id1_6_2_, user3_.time_created as time_cre2_6_2_, user3_.uuid as uuid3_6_2_, user3_.version as version4_6_2_, user3_.email_address as email_ad5_6_2_, user3_.first_name as first_na6_6_2_, user3_.hashed_password as hashed_p7_6_2_, user3_.is_verified as is_verif8_6_2_, user3_.last_name as last_nam9_6_2_, user3_.photo_id as photo_i10_6_2_, user3_.public_id as public_11_6_2_, user3_.role as role12_6_2_, user3_.user_status as user_st13_6_2_ from attachment_pages pages0_ inner join attachment_has_pages attachment1_ on pages0_.pages=attachment1_.id left outer join attachment attachment2_ on attachment1_.attachment_id=attachment2_.id left outer join user user3_ on attachment2_.user_id=user3_.id where pages0_.attachment=?
Hibernate: select sessiontok0_.id as id1_4_0_, sessiontok0_.is_keep_logged_in as is_keep_2_4_0_, sessiontok0_.last_updated as last_upd3_4_0_, sessiontok0_.time_created as time_cre4_4_0_, sessiontok0_.token as token5_4_0_, sessiontok0_.user_id as user_id6_4_0_ from session_token sessiontok0_ where sessiontok0_.id=?
Hibernate: select sessiontok0_.id as id1_4_0_, sessiontok0_.is_keep_logged_in as is_keep_2_4_0_, sessiontok0_.last_updated as last_upd3_4_0_, sessiontok0_.time_created as time_cre4_4_0_, sessiontok0_.token as token5_4_0_, sessiontok0_.user_id as user_id6_4_0_ from session_token sessiontok0_ where sessiontok0_.id=?
Hibernate: select sessiontok0_.id as id1_4_0_, sessiontok0_.is_keep_logged_in as is_keep_2_4_0_, sessiontok0_.last_updated as last_upd3_4_0_, sessiontok0_.time_created as time_cre4_4_0_, sessiontok0_.token as token5_4_0_, sessiontok0_.user_id as user_id6_4_0_ from session_token sessiontok0_ where sessiontok0_.id=?
sessiontok0_.user_id as user_id6_4_0_ from session_token sessiontok0_ where sessiontok0_.id=?
Hibernate: insert into session_token (is_keep_logged_in, last_updated, time_created, token, user_id) values (?, ?, ?, ?, ?)
Hibernate: select sessions0_.user_id as user_id6_6_1_, sessions0_.id as id1_4_1_, sessions0_.id as id1_4_0_, sessions0_.is_keep_logged_in as is_keep_2_4_0_, sessions0_.last_updated as last_upd3_4_0_, sessions0_.time_created as time_cre4_4_0_, sessions0_.token as token5_4_0_, sessions0_.user_id as user_id6_4_0_ from session_token sessions0_ where sessions0_.user_id=?

User Entity
@Entity
@Table(name = "user")
public class User extends BaseEntity {

    private String firstName;

    private String lastName;

    private String emailAddress;

    private String hashedPassword;

@Enumerated(EnumType.STRING)
private Role role;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", targetEntity = SessionToken.class, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.TRUE)
@Sort(type = SortType.NATURAL)
private SortedSet<SessionToken> sessions = Collections
        .synchronizedSortedSet(new TreeSet<SessionToken>(Collections
                .<SessionToken> reverseOrder()));

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", targetEntity = Attachment.class, orphanRemoval = true, fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.TRUE)
@Sort(type = SortType.NATURAL)
private List<Attachment> attachment = new ArrayList<Attachment>();

@OneToMany(mappedBy = "user", targetEntity = VerificationToken.class, cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.TRUE)
private List<VerificationToken> verificationTokens = new ArrayList<VerificationToken>();

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER)
private Set<SocialUser> socialUsers = new HashSet<SocialUser>();

....
}

UserRepo class
public interface UserRepository extends CrudRepository<User, Long> {

    @Query("select u from User u where uuid = ?")
    User findByUuid(String uuid);

}


text:
Q: Why does my OpenGL ES app crash on glDrawElements? I have developed a mobile game with OpenGL ES 3 on Xamarin (Which uses OpenTK). It's running fine on most devices, but crashes on some devices (HUAWEI Y5 lite). Unfortunately I don't get a detailed log of the error:
  #00  pc 0000000000093d2a  /vendor/lib/egl/libGLESv2_mtk.so
  #01  pc 000000000001c137  /vendor/lib/egl/libGLESv2_mtk.so
  #02  pc 000000000001eddf  /vendor/lib/egl/libGLESv2_mtk.so
  #03  pc 000000000001af75  /vendor/lib/egl/libGLESv2_mtk.so
  #04  pc 000000000001aabf  /vendor/lib/egl/libGLESv2_mtk.so (glDrawElements+54)
  #05  pc 000000000000ca0c  <anonymous>

I'm guessing it has something to do with my draw code or worse with some driver issues of the phone. I'm using the following code to render quads:
public void BeforeRender()
{
    // Use shader program.
    GL.UseProgram(shader.Program);

    // Enable transparency
    GL.Enable(EnableCap.Blend);
    GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

    // Use texture
    GL.ActiveTexture(TextureUnit.Texture0);
    GL.Uniform1(shader.UniformTexture, 0);

    // Only bind once for all quads
    GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);
}

public void Render(Sprite sprite, Vector4 color, Matrix4 modelViewProjection)
{
    // Set model view projection
    GL.UniformMatrix4(shader.UniformModelViewProjection, false, ref modelViewProjection);

    // Set color
    GL.Uniform4(shader.UniformColor, color);

    // Set texture
    GL.BindTexture(TextureTarget.Texture2D, sprite.TextureId);

    // Update attribute value Position
    GL.BindBuffer(BufferTarget.ArrayBuffer, sprite.Vbo);
    GL.VertexAttribPointer(shader.AttribVertex, 3, VertexAttribPointerType.Float, false, sizeof(float) * 5, IntPtr.Zero); // 3 + 2 = 5
    GL.EnableVertexAttribArray(shader.AttribVertex);

    // Update attribute value TexCoord
    GL.VertexAttribPointer(shader.AttribTexCoord, 2, VertexAttribPointerType.Float, false, sizeof(float) * 5, new IntPtr(sizeof(float) * 3));
    GL.EnableVertexAttribArray(shader.AttribTexCoord);

    // Draw quad
    GL.DrawElements(BeginMode.Triangles, faceIndexes.Length, DrawElementsType.UnsignedShort, IntPtr.Zero);
}

public void AfterRender()
{
    // Unbind / Disable
    GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
    GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
    GL.Disable(EnableCap.Blend);
}

To draw multiple quads I just call the methods like this:
BeforeRender();

foreach(var sprite in sprites)
{
    Render(sprite);
}

AfterRender();

Is there something wrong with my code in general which might cause problems on some devices which other devices "tolerate"?
Thanks in advance!
Update:
Here is how I create the buffers:
public int Load<T>(T[] data)
        where T : struct
    {
        int bufferId;

        GL.GenBuffers(1, out bufferId);

        bufferIds.Add(bufferId);

        GL.BindBuffer(BufferTarget.ArrayBuffer, bufferId);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

        return bufferId;
    }

For the index buffer i use:
ushort[] faceIndexes =
        {
            0, 1, 2, 1, 3, 2
        };

indexBufferId = bufferManager.Load(faceIndexes);

For the vertex buffer I use:
float[] vertices =
            {
                0f, 0f, 0f, 0f, ty,
                width, 0f, 0f, tx, ty,
                0f, height, 0f, 0f, 0f,
                width, height, 0f, tx, 0f
            };

int vboId = bufferManager.Load(vertices);

A: The indices have to be store to an ElementArrayBuffer rather than an ArrayBuffer:
GL.BindBuffer(BufferTarget.ArrayBuffer, bufferId); ...
GL.BindBuffer(BufferTarget.ElementArrayBuffer, bufferId);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

Add a target argument to the generic Load method. For instance:
public int Load<T>(T[] data, BufferTarget target)
    where T : struct
{
    int bufferId;
    GL.GenBuffers(1, out bufferId);
    bufferIds.Add(bufferId);

    GL.BindBuffer(target, bufferId);
    GL.BufferData(target, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
    GL.BindBuffer(target, 0);

    return bufferId;
}

indexBufferId = bufferManager.Load(faceIndexes, BufferTarget.ElementArrayBuffer);

int vboId = bufferManager.Load(vertices, BufferTarget.ArrayBuffer);

A: I have found the issue, that was causing my app to crash on some devices. Apparently there was an item slipping in to the drawing routine, which was passing a buffer id 0 into GL.BindBuffer. On some devices this was causing the following error when Gl.DrawElements was called: emuglGLESv2_enc: sendVertexAttributes: bad offset / len!!!!!
The solution was of course to not execute this code anymore whenever the buffer id is 0 or no buffer for the id was created.
In my case the 0 was not returned by GL.GenBuffers. I had some sprites which should be empty (not rendered), and my orignal solution was to set the buffer id to 0.


text:
Q: Why this tab layout doesn't stay in the bottom? I've created my application with Navigation Drawer. In my Activity I put this code:
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{

 protected void onCreate(Bundle savedInstanceState)
 {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
{
    public void onDrawerOpened(View view)
    {
        super.onDrawerOpened(view);
    }
    public void onDrawerClosed(View v)
    {
        super.onDrawerClosed(v);
    }
};
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
onNavigationItemSelected(navigationView.getMenu().getItem(0));
navigationView.setNavigationItemSelectedListener(this);
}

 public boolean onCreateOptionsMenu(Menu menu) {

 getMenuInflater().inflate(R.menu.menu, menu);
return true;
}

public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();

if (id == R.id.action_settings)
{
    return true;
}

 return super.onOptionsItemSelected(item);
}

 public boolean onNavigationItemSelected(MenuItem item) {

  Fragment fragment = null;
   String title = null;
int id = item.getItemId();
Class fragmentClass=null;

if (id == R.id.Home)
{
  fragmentClass = HomeFragment.class;
  title="Home";

}
else if (id == R.id.Profile)
{
  fragmentClass= ProfileFragment.class;
  title="Profile";
}
try {
    fragment = (Fragment) fragmentClass.newInstance();
} catch (InstantiationException e) {

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

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,      fragment).commit();

if (getSupportActionBar() != null)
{
    getSupportActionBar().setTitle(title);
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);

return true;
}

now in the HomeFragment I want to put a tab in the bottom of the screen. So i put this code:
public class HomeFragment extends Fragment {

public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

}

public View onCreateView(LayoutInflater inflater, ViewGroup       container, Bundle savedInstanceState) {

View inflatedView = inflater.inflate(R.layout.fragment_home, null);

tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabs);
viewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager);

viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

tabLayout.post(new Runnable() {
    @Override
    public void run() {
        tabLayout.setupWithViewPager(viewPager);
    }
});

return inflatedView;

 }

class MyAdapter extends FragmentPagerAdapter {

public MyAdapter(FragmentManager fm) {
    super(fm);
}

/**
 * Return fragment with respect to Position .
 */

@Override
public Fragment getItem(int position)
{
    switch (position){
        case 0 : return new SearchFragment();
        case 1 : return new CardFragment();
        case 2 : return new MapFragment();
    }
    return null;
}

public int getCount() {

    return int_items;

}

This is fragment_home.xml:
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:background="@color/material_blue_grey_800"
        app:tabIndicatorColor="@color/black_overlay"
        app:tabSelectedTextColor="#000"
        app:tabTextColor="#FFFFFF"
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/tabs">

    </android.support.v4.view.ViewPager>

    </RelativeLayout>
</FrameLayout>

and this the activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_menu"
        app:menu="@menu/activity_menu_drawer" />

</android.support.v4.widget.DrawerLayout>

But finally I get this result:

How could I put this tabLayout in the toolbar?

A: You don't need to take frame layout for fragment_home as root layout. Simplify your xml file as:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:background="@color/material_blue_grey_800"
        app:tabIndicatorColor="@color/black_overlay"
        app:tabSelectedTextColor="#000"
        app:tabTextColor="#FFFFFF"
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/tabs">

    </android.support.v4.view.ViewPager>

    </RelativeLayout>


text:
Q: Eagle: Circular area under component colliding with traces I am creating a PCB layout in Eagle and I noticed that when I add in the ground plane, there are two unfilled circular areas under the usb mini type B socket.  Does that area need to be empty?
I have some traces going under the USB socket, is it okay if I leave them there?


text:
Q: Parent components show over child form I've been following the below page in order to have a child Form that I can click on its components (such as an edit) and have proper focus:
Working with MDI Forms in Delphi
The problem now is that the components on the parent Form show on top of the child Form. If I use the SendToBack() command for those components, they completely disappear. Here is a screenshot of what happens:

EDIT:
I have a Form with buttons and a ListView that displays client info. When I click on a client, I can click a button to view or edit that client, alternatively add a new one. The Edit/Add pops up a Form where I can input the info and save it. I'm using an OnClick event for each Edit that has a SetFocus(). That gets focus on each Edit, but then all the text is selected, so I cannot click on the line and start editing text - it just overrides unless I use an arrow first.
Initially, I used regular Forms and that's where I had the focus issue. MDI fixed that, but now it's the parent components that show on top of the child.

A: Concerning MDI forms: that is how MDI works. The main form is not supposed to have anything else than a menu bar and optionally a toolbar, aligned alTop. The child forms use the rest of the space. Well as @RemyLebeau suggested, you can add other controls too, if you align them.
But it turned out that the actual problem with using ordinary secondary forms was that the text in an edit control on the secondary form becomes selected when you set focus to the edit control in a button click. That is easy to change, right after you set the focus to an edit control:
Edit2.SelLength := 0; // nothing selected, cursor at beginning

Edit3.SelStart := Length(Edit3.Text); // nothing selected, cursor at end of text


text:
Q: Using CustomStringConvertible in UITableView I've declared the following:
class Song: CustomStringConvertible {
    let title: String
    let artist: String

    init(title: String, artist: String) {
        self.title = title
        self.artist = artist
    }

    var description: String {
        return "\(title) \(artist)"
    }
}

var songs = [
    Song(title: "Song Title 3", artist: "Song Author 3"),
    Song(title: "Song Title 2", artist: "Song Author 2"),
    Song(title: "Song Title 1", artist: "Song Author 1")
]

I want to enter this information into a UITableView, specifically at the tableView:cellForRowAtIndexPath:.
Such as this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

    cell.titleLabel = //the song title from the CustomStringConvertible[indexPath.row]
    cell.artistLabel = //the author title from the CustomStringConvertible[indexPath.row]
}

How would I do this? I can't figure it out.
Thanks a lot!

A: I think you may be conflating CustomStringConvertible with some other design patterns. First, an answer:
// You have some container class with your tableView methods
class YourTableViewControllerClass: UIViewController {

    // You should probably maintain your songs array in here, making it global is a little risky

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

        // Get the song at the row
        let cellSong = songs[indexPath.row]

        // Use the song
        cell.titleLabel.text = cellSong.title
        cell.artistLabel.text = cellSong.artist
    }
}

Because the cell's title/artist are already public strings, you can just use them as you need. CustomStringConvertible will allow you to use the actual object itself as a String. So, in your case, you could have a song and call song.description and it would print out "title artist". But if you want to use the song's title and artist, you should just call song.title and song.artist. Here's the documentation on that protocol.
Also, as I wrote above, try moving your songs array into your ViewController. And maybe consider using structs instead of classs for your Song type.

A: First, your Controller must implement UITableViewDataSource.
Then,
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell
    cell.titleLabel?.text = songs[indexPath.row].title
    cell.artistLabel?.text =songs[indexPath.row].artiste
}


text:
Q: UIAlertController from Inside the AppDelegate I am trying to present UIAlertController from inside AppDelegate and I am getting all sort of errors:
I have @import UIKit; at the top.
What am I doing wrong?
UPDATE: Here is the code:
  switch (accountStatus)
    case CKAccountStatusCouldNotDetermine:
    case CKAccountStatusNoAccount:
    case CKAccountStatusRestricted:

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"My Alert" message:@"This is an alert." preferredStyle:UIAlertControllerStyleAlert];

        break;

If I remove the UIAlertController line then everything is fine! The error just says Parse Issue, Expected Expression. thats it

A: You can not create a local variable in a switch statement like that without introducing a new scope. Logical ORing the enumeration values together is also probably not what you want - you can instead have the cases fall through.
switch (accountStatus) {

  case CKAccountStatusCouldNotDetermine:
  case CKAccountStatusCouldNoAccount:
  case CKAccountStatusCouldRestricted: {
    UIAlertController *controller =
      [UIAlertController alertControllerWithTitle:@"My Alert"
                                          message:@"This is an alert."
                                   preferredStyle:UIAlertControllerStyleAlert];
  } break;

}

You'll obviously need to have some kind of context to present this viewController but your code listing does not show enough to provide any further code


text:
Q: Perform multiples pivot_longer in a data frame So this is my data, each row corresponds to a nest and in each row we have 3 chick CHICK_RING1, CHICK_RING2, CHICK_RING3 with their age and body condition.
data = wrapr::build_frame(
  "YEAR"  , "Nest"   , "Clutch", "RINGMALE", "RINGFEMALE", "CHICK_RING_1", "CHICK_RING_2", "CHICK_RING_3", "LastAge1", "LastAge2", "LastAge3", "RealMotherAge", "RealFatherAge", "BODYCOND1", "BODYCOND2", "BODYCOND3" |
    "2002", "02-125" , "3"     , "A72"    , "C15"      , "K67"        , "K75"        , "K82"        , "90"      , "90"      , "68"      , "9"            , "14"           , "7.070707" , "9.086538" , "8.622449"  |
    "2008", "08-155" , "3"     , "A72"    , "C15"      , "S09"        , "R30"        , "R40"        , "75"      , "72"      , "73"      , "15"           , "20"           , "7.075472" , "6.984925" , "7.511962"  |
    "2006", "06-267" , "3"     , "A72"    , "C15"      , "O30"        , "O37"        , "O59"        , "73"      , "70"      , "66"      , "13"           , "18"           , "9.227273" , "8.232323" , "9.44186"   |
    "1999", "99-925" , "3"     , "A39"    , "A76"      , "I00"        , "I15"        , "I73"        , "70"      , "69"      , "72"      , "10"           , "10"           , "7.989691" , "7.882883" , "8.043478"  |
    "2011", "11-0305", "3"     , "A66"    , "P48"      , "W25"        , "W30"        , "W46"        , "68"      , "68"      , "68"      , "4"            , "22"           , "7.675676" , "10.4186"  , "7.352941"  )

I would like to perform a pivot_longer to have a data frame with 15 rows and in each row the chick ID with their body condition, chick age (lastAge), parents age, year, nest and clutch.
One solution would be to create 3 data sets for each chick  but in prefer something with the tidyverse.
Thanks

A: You should pivot twice:
library(tidyverse)
data %>%
  pivot_longer(cols = all_of(ends_with(c("1","2","3"))), names_to = c("stat", "CHICK_ID"), names_pattern = "(.*)(.)") %>%
  pivot_wider(names_from = "stat") %>%
  mutate(across(-c("Nest", "RINGMALE", "RINGFEMALE", "CHICK_RING_"), as.numeric))

The names_pattern is a regular expression that will match two groups, each between the parentheses.  The (.) will match any single character.  The (.*) will match as many characters as it can, while still allowing the (.) at the end to capture the last character.
The first pivot_longer will convert most of your data to characters.  You can coerce them back with the mutate(across(...)).


text:
Q: On any Stack Exchange site, links included in the Help Center lead to help pages on Stack Overflow On any Stack Exchange site (for example here), the help page about Help Center > Answering > How to reference material written by others (….stackexchange.com/help/referencing) shows a short list including two links:

*

*Provide a link to the original page or answer

*Quote only the relevant portion

*Provide the name of the original author

On any site, both links lead to help pages on Stack Overflow (https://stackoverflow.com/editing-help#links and https://stackoverflow.com/editing-help#simple-blockquotes, respectively).
However, since the corresponding help pages are also available on each individual Stack Exchange site (for example here and here), the links should point to the respective site instead.

A: For some reason that particular page had the domains explicitly as part of the links. I looked at some various other help pages and those ones didn't exhibit the same problem, but these ones have been fixed.
Let us know if you find other pages which have incorrect links like this.


text:
Q: Cauchy-Schwarz inequality for vectors, proof? The proof I have written for the Cauchy-Schwarz inequality for vectors is below:

*

*I would be grateful if anyone could spot and errors or inefficiencies?

*Can this proof be easily adapted to cover complex numbers also?

Many thanks for your help.
Theorem
$||u||\space ||v|| \geq |\left \langle u,v \right \rangle|$, where $u,v∈V=\Bbb R^n$.
Proof
If $v=0$, $|\left \langle u,0 \right \rangle|=||u||\space ||0||$, therefore $0=0$, similarly for $u=0$.
For $u,v \neq 0$, we need a vector orthogonal to $u_v$ then we can use the Pythagorean Theorem to prove. The standard formula to make $z$ a projection of $u$, orthogonal to $v$ is $z=u-\frac{\left \langle u,v \right \rangle}{\left \langle v,v \right \rangle}v$.
As $v$ and $z$ are orthogonal we can apply the Pythagorean Theorem, as the length of the hypotenuse $u$ is greater than the length of $u_v$:
$||u||^2 = ||u - \frac{\left \langle u,v \right \rangle}{\left \langle v,v \right \rangle}v||^2 + ||\frac{\left \langle u,v \right \rangle}{\left \langle v,v \right \rangle}v||^2 \geq ||\frac{\left \langle u,v \right \rangle}{\left \langle v,v \right \rangle} v||^2 = \frac{|\left \langle u,v \right \rangle|^2} {(||v||^2)^2}||v||^2 = \frac{|\left \langle u,v \right \rangle|^2} {||v||^2}$.
$\implies ||u||^2 \geq \frac{|\left \langle u,v \right \rangle|^2} {||v||^2}$
$\implies ||u||^2 ||v||^2 \geq |\left \langle u,v \right \rangle|^2$
$\implies ||u|| \space ||v|| \geq |\left \langle u,v \right \rangle|$
Q.E.D.

A: The only subtlety in the complex case is whether to define $z$ as $u-\frac{\langle u,\,v\rangle}{\langle v,\,v\rangle}v$ or $u-\frac{\langle v,\,u\rangle}{\langle v,\,v\rangle}v$; either would work in the real case, but$$\Vert u-zv\Vert^2=\Vert u\Vert^2+|z|^2\Vert v\Vert^2=2\Re\Vert u,\,zv\Vert^2$$implies $z$ needs to be $\tfrac{\langle u,\,v\rangle}{\langle v,\,v\rangle}$ ($\tfrac{\langle v,\,u\rangle}{\langle v,\,v\rangle}$) if the inner product is linear (antilinear) in the rightmost argument, which is convention of physicists (mathematicians).


text:
Q: Custom button with a selection I don't know if this has been asked before. I am going to be building a calculator for my dad. He asked me if there is any way to have customization with the buttons.
I have not done any code yet. I plan on trying a few things. My research has come up with nothing.
This is what I am trying to accomplish, I have a feeling it breaks the android studio law of coding. This is the concept:
Imagine the calculator. You have 8 blank buttons above the numbers. Those buttons ordinarily have the functions such as percent and sqrt.,..etc.
I have been asked if it's possible can he just hold the button and change those functions at will.
So the question at hand is. Can I do if statements to change the symbol and the code for a particular button when long pressed?
The concept of the calculator would be in portrait mode he can customize the buttons to the functions he uses without having to turn the calculator in landscape mode?
So in theory you have a long press which would bring up a selector. He can select any math function and based on that function the symbol and code would change and the button will work properly to the new selection?
I was going to to build the calculator as a standard. But was also wondering myself if this is possible. I know the buttons serve as a one function but in coding anything is possible.
Any help or advice would be appreciated. If this can be done it opens new possibilities to app features to only show what you want and not a predefined controls.
*******once I try a few codes I will edit question to better see the issue and what I am trying to do.

A: *

*OnLongPress show a dialog with the option you want and change the button text according to selected option.

*On Onclick check the button text and call function according to the text


text:
Q: Gallery can't display image from internal storage I have image stored in the internal storage of the app. I can grab the path and I can succesfully set it to image view. But when  I am trying to let the user open it using the gallery (intent), it displays black screen.
myIntent.setDataAndType(Uri.fromFile(file), mimetype);
intent = Intent.createChooser(myIntent, "Choose a viewer");
startActivity(intent);

I am pretty sure it has to do with permission that gallery cant access private storage of my app for some reason. But is there way to do that "beside moving the file to external storage"
Thanks

A: Use FileProvider to serve the file from internal storage. Quoting the documentation:

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.
A content URI allows you to grant read and write access using temporary access permissions. When you create an Intent containing a content URI, in order to send the content URI to a client app, you can also call Intent.setFlags() to add permissions. These permissions are available to the client app for as long as the stack for a receiving Activity is active.

A: Here is an easy 'single file based solution'
When ever you add a file, let Media Store Content Provider knows about it using
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                       Uri.fromFile(imageAdded)));

A: i have done some thing like this to show images from gallery.
private void pickFromGallery() {
    Crop.pickImage(this);
}

<--->
crop is an android class.
this is a function in crop class.
public static void pickImage(Activity activity) {
    Intent intent = (new Intent("android.intent.action.GET_CONTENT")).setType("image/*");

    try {
        activity.startActivityForResult(intent, 9162);
    } catch (ActivityNotFoundException var3) {
        Toast.makeText(activity, string.crop__pick_error, 0).show();
    }

}


text:
Q: Schedule weekly import of documents from external location I want to schedule a weekly batch import of documents from an external drive into Salesforce.
Say, in the external drive there is a folder called  'CompetitorScore' and in that folder there are 50 files (pdf document), each for one of the AccountRecord in Salesforce. I want to get each of the Attachment and relate it to correct Account in salesforce.
Every Week the old files in the external drive will be deleted, and new ones inserted. I want to be able to do the same in Salesforce when the weekly import happens. Delete the old attachment from AccountRecord, and replace with new attachment.
I think this may not be possible with Dataloader or free version of Dataloader.io, would this be possible with free version of Jitterbit
If not what would be my options?
Thank You !.


text:
Q: pulling image to pod from docker hub registry throwing error Context Exceed Timeout I am facing error while pulling image into pod by docker hub registry. first it goes to images pulling for 200s then after through error that

A: Thankyou everyone for the help basically I was running on minikube on ubuntu and ubuntu is my virtual machine I did not sync environment of minikube with docker when  kubelet look for image it check within minikube images and images was not availble when I synced pod started running


text:
Q: Chrome not honoring https in relative URLs I having a site that loads perfectly fine in Firefox and IE, but is being blocked by Chrome. Chrome is complaining about mixed mode content, however all resources are accessed by relative URLs within the same domain.
From my understanding, a relative URL should use the same protocol as the "main" page that is being loaded. That being the case I have the following:
<link href="/assets/css/small.css" title="Small" rel="alternate stylesheet" type="text/css" />
<link href="/assets/css/large.css" title="Large" rel="alternate stylesheet" type="text/css" />

Both are Relative URLs. When the page is loaded via HTTPS I get the following from the Chrome Console (I change the domain name for my client's privacy):

    [blocked] The page at https://www.example.com/Login/ ran insecure
    content from http://www.example.com/assets/css/small.css.

    [blocked] The page at https://www.example.com/Login/ ran insecure content from
    http://www.example.com/assets/css/large.css.

Am I wrong in the assumption that relative URLs should honor the requested protocol?
UPDATE:
It is also blocking .js files referenced the same way:
<script src="/assets/scripts/change-text-size.js" type="text/javascript"></script>

is being blocked:

[blocked] The page at https://www.example.com/Login/ ran insecure content from http://www.example.com/assets/scripts/change-text-size.js.

Another weird thing is that if I do view-source on the page that is having the issue, I see the relative url and if I hover the cursor over the "link" to the asset (stylesheet, .js file) the tooltip DOES say it is https:.
Update 2:
There is nothing referenced in the .css file. Here is the entire contents of the "small.css" file mentioned above:
div#content-wrap,
div#content-one-col
{
    font-size: 65%;
}

A: In your public example, the static assets are redirecting to the http version, causing Chrome to complain.
Eg if you go to https://www.bayerglucofacts.com/assets/css/de-de.css - you get a 302 redirect to http://www.bayerglucofacts.com/assets/css/de-de.css which gives the error.

A: I've been having the same problem, and this was due to a <base> tag pointing to the non-SSL version of the site.
However, as ScottR pointed out, this was due to your CSS redirecting to the non-SSL version. It seems that is fixed now - don't forget to accept his answer though!

A: It seems most likely that a link inside the css is pointing to an http image/resource.