text: Q: InstallShield MVC2 Application deployment on IIS I want to be able to deploy a MVC2 application as a web application on IIS using the installshield. When I try to deploy the application it just simple copies the whole solution to IIS instead of converting it to a web application. I created an MSI using VS2010 which converts the code into web application and then called that through installshield installer (which basically does some other stuff as well). But it creates two references in installed programs visible through Add/Remove Programs which in turn makes me uninstall both in order to completely remove the application. Any suggestions on how to go about at this?


text:
Q: Issues with Graphics.CopyFromScreen due to dpi or screen resolution changes I am trying to take a screenshot of a contents of a Windows Forms panel when the user clicks on the print button. I am using Graphics.CopyFromScreen with the parameter sourceX and sourceY will be the location of the panel corresponding to the parent control.
The issue is that when the user changes the Dpi or screen resolution, the X and Y coordinate for the location of the panel is different. So the screenshot image is cut off. Any advise ?

A: You have to work with screen coordinates, not relative coordinates.
Find Coordinates for point on screen?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fanny's Occurences Fanny is given a string along with the string which contains single character x. She has to remove the character x from the given string. Help her write a function to remove all occurrences of x character from the given string.
Input Specification:
Input 1: input string s
Input 2: String containing any character x
Output Specification:
String without the occurrence of character x
Example 1:
Input:
welcome to mettl
l
Output:
wecome to mett
Explanation: As I is the character which is required to be removed, therefore all the occurrences of I are removed, keeping all other characters.
Example 2:
input1: I out of Rings
Input2: o
Output: I ut f Rings
MY solution:
def extractSecretMessage(Str, Sub):
    Str= Str.replace(Sub, " ")
    return Str.strip()
Str = input("")
Sub = input("")
print(extractSecretMessage(Str, Sub))

ERROR:
Input (stdin)
Tamilarasan guna
a
Your Output (stdout)
T mil r s n gun
Expected Output
Tmilrsn gun
Compiler Message
Nice try, But you did not pass the test case!

A: The problem is that when you are supposed to remove a character, you are replacing it with a space, when you should be replacing it with an empty string.
Another potential problem (although not exposed in these examples) is that you are calling strip() (which will remove leading and trailing whitespace) when the specification does not say that you are meant to do this.  (In some cases, it could mask the previous bug, if the space that you wrongly added was at the start or end of the string.)
Where you have:
    Str= Str.replace(Sub, " ")
    return Str.strip()

you should use:
    Str= Str.replace(Sub, "")
    return Str

or simply:
    return Str.replace(Sub, "")


text:
Q: Looking for a host based network monitor solution Hi all!
Problem
So, my hosting company has a network usage graph for my dedicated server. It seems that one day earlier this month, my network usage suddenly spiked with several hundred megabytes transferred (usually it's in the tens, not hundreds). It was probably me, but i just can't be sure who or what it was.
Question
So my question is; does anyone know of any host based solution for monitoring network usage that would tell me the client's IP-address, the port/service he/she used?
What I don't want
I'm just guessing that someone will suggest i use nagios, munin, zabbix, cacti, mrtg - I've also looked at those, but a graph over network usage will not give me the answers I'm looking for. :-)
Almost there
I've already looked at a lot of monitoring solutions, and I've tried [ntop][http://www.ntop.org/], [darkstat][http://unix4lyfe.org/darkstat/] and others. Darkstat just didn't give me the answers. Although it listed a lot of statistics, and i could list the clients - it doesn't show me the network usage for a particular period. Ntop is by far the best I've seen so far - but i think it mostly shows current network usage, not the historical part. I could run apt-get upgrade and download a whole bunch of software, but not see it in the log afterwards.

A: netflow tools + flow generator of some sort will get you report that you are looking for. Also this. If you are confused about how to use flow-tools to generate a report that you need you can start here

A: You mentioned ntop which I think is probably the best answer for the type of query you have.  I run ntop in an "as needed" capacity rather than leaving it going all the time.
If you have any idea on how to reproduce the spike in traffic, I'd start ntop first and then pay attention to your traditional bandwidth graphs.  Once you recreate the problem, switch over to ntop's interface which gives you several methods to "drill down" on the data.  Your problem host should be easy to spot.

A: For adhoc monitoring I would recommend iptraf. It shows all currently open connections with IP addresses and the number of packets and bytes in both directions. It does, however, not support historical data (from what I know, but then maybe somebody else knows more about that).
You could try and just capture traffic using tcpdump. You probably have to limit the capture size to the bare minimum, and then try and analyze that data later with wireshark or other tools that can analyze pcap files.


text:
Q: How to run a js file from windows terminal? In order to have the measurements displayed of a photocell linked to an Arduino on the terminal, Iam trying to execute a node.js server. It's from a tutorial made by Adil Moujahid
I tried to follow the following:

from you terminal go to the folder where server1.js is saved, and execute node server1.js.

Yet, I was advised by this answer (the second one) not to use Node.js but rather the CMD terminal.
So despite of my lack ok knowledge of the commands of this terminal (I learned Linux) I went to this terminal, went to the directory where server1.js is(C:\Users\Antoine\Documents\Arduino\Connected Objects\sketch_jan30a) with cd and did:
Wscript.exe Automation \Framework\server1.js

Which didn't work so I tried
Wscript.exe \Framework\server1.js

Wich didn't work and sent me a windows Script error:

So I thought something was wrong with server1.js code:
var serialport = require('serialport');
var portName = '/dev/tty.usbmodem1411';
var sp = new serialport.SerialPort(portName, {
    baudRate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false,
    parser: serialport.parsers.readline("\r\n")
});

sp.on('data', function(input) {
    console.log(input);
});

Is there something wrong with portname? It's my best guess from what's written by the tutorial made by Adil Moujahid and from what is written on the message.
Can you help me either to write execute the .js file or tell me if something's wrong in my code (in this case I will try to move this question to a more appropirate forum)

A: The answer to your other question told you to run NPM commands outside of the node.js terminal. npm is a keyword that tells the command prompt to use a particular application to process the commands or arguments. In your case you're trying to run a js server written for node.js so rather than using npm install ... you would use probably use node server1.js (if you're trying to run it outside of the node.js terminal window, after cd'ing to the appropriate directory)
Sorry, just saw this question is old. Hopefully you got it by now and this post will help someone else just learning.

A: The code is fine, but it was written for a different runtime. WScript is very different from node.js (just like both are different from the "usual" web-browser environment) – for example, it does not support require() nor console. (Technically it's not even JavaScript but JScript.)
You will have to download node.js for Windows.


text:
Q: combinar correspondencia Excel y PowerPoint dos Diapositivas vba Tengo problemas al crear correspondencia Excel y PowerPoint dos Diapositivas, cuando ejecuto el código para una solo si reemplaza el contenido, cuando trato de ejecutar para dos diapositivas no funciona el código pueden ayudarme en observar donde esta el error
Sub Combinar()
    Set objSld = objPres.Slides.Range(Array(1, 2)).Duplicate
    For Each objSld In objSld.Shapes.Range(Array(1, 2))
                   If objSld.HasTextFrame Then
                        If objSld.TextFrame.HasText Then
                            objSld.TextFrame.TextRange.Replace "<NOMBRE>", strNombre
                            objSld.TextFrame.TextRange.Replace "<CARGO>", strCargo
                            objSld.TextFrame.TextRange.Replace "<DNI>", strDNI
                            objSld.TextFrame.TextRange.Replace "<FOTO>", strFoto
                            objSld.TextFrame.TextRange.Replace "<fdemision>", strFechaIn
                            objSld.TextFrame.TextRange.Replace "<fdvencimiento>", strFechaVen
                       End If
                    End If
                Next
End Sub


text:
Q: slow training despite using tf data pipeline I am training image classification model which contains 21000 image. I have created data pipeline with the help of tf.data API of tensorflow. My issue is that training is too slow despite using API. I have also enabled tensorflow gpu version. Please help me out.I thought first it was due to keras imagedatagenerator which is slowing down my training time but now when I changed it tf.data pipeline it still does not utilizes my gpu. Below is my whole code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras import models, layers
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.applications import ResNet50, EfficientNetB3, InceptionV3, DenseNet121
from tensorflow.keras.optimizers import Adam

# ignoring warnings
import warnings
warnings.simplefilter("ignore")
import os,cv2

base_dir = "D:/cassava-leaf-disease-classification/"
train_csv = pd.read_csv("D:/cassava-leaf-disease-classification/train.csv")
# print(train_csv.head())
df_sample = pd.read_csv("D:/cassava-leaf-disease-classification/sample_submission.csv")
train_images = "D:/cassava-leaf-disease-classification/train_images/"+train_csv['image_id']
# print(train_images)

# print(os.listdir(train_images))
train_labels = pd.read_csv(os.path.join(base_dir, "train.csv"))

# print(train_labels)
BATCH_SIZE = 16
EPOCHS = 25
STEPS_PER_EPOCH = len(train_labels)*0.8 / BATCH_SIZE
TARGET_SIZE = 300
# train_labels['label'] = train_labels.label.astype('str')
labels = train_labels.iloc[:,-1].values
# print(labels)

def build_decoder(with_labels=True, target_size=(TARGET_SIZE, TARGET_SIZE), ext='jpg'):
    def img_decode(img_path):
        file_bytes = tf.io.read_file(img_path)
        if ext == 'png':
            img = tf.image.decode_png(file_bytes, channels=3)
        elif ext in ['jpg', 'jpeg']:
            img = tf.image.decode_jpeg(file_bytes, channels=3)

        else:
            raise ValueError("Image extension not supported")

        img = tf.cast(img, tf.float32) / 255.0
        img = tf.image.resize(img, target_size)

        return img

    def decode_with_labels(img_path, label):
        return img_decode(img_path), label

    if with_labels == True:
        return decode_with_labels

    else:
        return img_decode

def build_augmenter(with_labels=True):
    def augment(img):
        img = tf.image.random_flip_left_right(img)
        img = tf.image.random_flip_up_down(img)
        img = tf.image.random_brightness(img, 0.1)
        img = tf.image.random_contrast(img, 0.9, 1.1)
        img = tf.image.random_saturation(img, 0.9, 1.1)
        return img

    def augment_with_labels(img, label):
        return augment(img), label

    if with_labels == True:
        return augment_with_labels

    else:
        return augment

def build_dataset(paths, labels=None, bsize=32, cache=True,
                  decode_fn=None, augment_fn=None,
                  augment=True, repeat=True, shuffle=1024,
                  cache_dir=""):
    if cache_dir != "" and cache is True:
        os.makedirs(cache_dir, exist_ok=True)

    if decode_fn is None:
        decode_fn = build_decoder(labels is not None)

    if augment_fn is None:
        augment_fn = build_augmenter(labels is not None)

    AUTO = tf.data.experimental.AUTOTUNE
    slices = paths if labels is None else (paths, labels)

    dset = tf.data.Dataset.from_tensor_slices(slices)
    dset = dset.map(decode_fn, num_parallel_calls=AUTO)
    # dset = dset.cache(cache_dir) if cache else dset
    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset
    dset = dset.repeat() if repeat else dset
    dset = dset.shuffle(shuffle) if shuffle else dset
    dset = dset.batch(bsize).prefetch(AUTO)

    return dset

# Train test split
(train_img, valid_img,train_labels,valid_labels) = train_test_split(train_images,labels,train_size = 0.8,random_state = 0)
# print(train, valid)

# Tensorflow datasets
train_df = build_dataset(
    train_img, train_labels, bsize=BATCH_SIZE,
    cache=True)

valid_df = build_dataset(
    valid_img, valid_labels, bsize=BATCH_SIZE,
    repeat=False, shuffle=False, augment=False,
    cache=True)

def create_model():
    model = models.Sequential()
    model.add(EfficientNetB3(include_top=False, weights='imagenet',
                             input_shape=(TARGET_SIZE,TARGET_SIZE,3)))
    model.add(layers.GlobalAveragePooling2D())
    model.add(layers.Dense(5,activation='softmax'))
    model.compile(optimizer=Adam(lr=0.001),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    return model

model = create_model()
model.summary()

model_save = ModelCheckpoint('C:/Users/rosha/PycharmProjects/CLDD/saved_Models/EffNetB3_300_16_best_weights.h5',
                             save_best_only=True,
                             save_weights_only=True,
                             monitor='val_accuracy',
                             mode='max',
                             verbose=1
                             )

early_stop = EarlyStopping(monitor='val_accuracy',
                           min_delta=0.001,
                           patience=5,
                           mode='max',
                           verbose=1)

reduce_lr = ReduceLROnPlateau(monitor='val_accuracy',
                            factor=0.3,
                            patience=2,
                            min_delta=0.001,
                            mode='max',
                            verbose=1)

history = model.fit(
    train_df,
    validation_data=valid_df,
    steps_per_epoch=STEPS_PER_EPOCH,
    epochs=EPOCHS,
    callbacks=[model_save, early_stop, reduce_lr],
    verbose=1,
)

plt.rcParams.update({'font.size': 16})
hist = pd.DataFrame(history.history)
fig, (ax1, ax2) = plt.subplots(figsize=(12, 12), nrows=2, ncols=1)
hist['loss'].plot(ax=ax1, c='k', label='training loss')
hist['val_loss'].plot(ax=ax1, c='r', linestyle='--', label='validation loss')
ax1.legend()
hist['accuracy'].plot(ax=ax2, c='k', label='training accuracy')
hist['val_accuracy'].plot(ax=ax2, c='r', linestyle='--', label='validation accuracy')
ax2.legend()
plt.show()

model.save('./EffNetB3_300_16.h5')

A: So here is a small checklist I like to go over:

*

*Execute the following code to check whether the GPU is found by tensorflow:

import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))

*If the output is "Num GPUs Available: 0", then you should check that you indeed have tensorflow-gpu installed, you might also want to check that support libraries are also in the gpu version.

*If your libraries are correct you will need to check to see if your CUDA driver installation is correct. This step is somewhat OS dependent but there are many tutorials online for both. My favourite for TF can be found on the official website: https://www.tensorflow.org/install/gpu


text:
Q: Margin negativo é uma prática ruim? Utilizar uma margin com valor negativo é uma prática ruim (bad practice)?
Exemplo:
margin-top: -3px;

A: Não, margem negativa em CSS não é uma má prática. Margem negativa é um ótimo caminho para se negar paddings em um elemento, quando algum elemento interno deve ser posicionado de tal maneira.
Também, acho que a única maneira 100% confiável, suportada por todos os browsers, de se centralizar um elemento vertical e horizontalmente em relação a um elemento pai, é se utilizando de margem negativa, como segue o exemplo:
.classe_css{
  left:50%;
  top:50%;
  position: relative;
  margin-left:-40px; /* -1/2 width */
  margin-top:-40px; /* -1/2 height */
}

A: Margin negativa não é necessariamente uma pratica ruim, por exemplo você consegue utilizar a técnica de faux-columns sem imagens.

Negative values for margin properties are allowed, but there may be implementation-specific limits.

— W3C, sobre margin properties
Esse trecho foi retirado de uma discussão no iMasters sobre o mesmo assunto.
Dá uma lida neste  artigo aqui, ele explica formas de utilizar margens negativas, mostrando formas comuns e erros também.


text:
Q: How to toggle dropdown navigation menu? something is wrong with my code, here is what it should do, but doesn't.^^
E.g. on click on "nav 1", slide down and fadein subnavigation, than on click on "nav 2", fade sub navigation 1 out and fade sub navigation 2 in.
This is what I have so fare:
var nav = $('.nav li.mega');
nav.children('.subnav-container').slideUp(0);
nav.click(function (e) {
    e.preventDefault();
    nav.children('.subnav-container').slideUp(500);
    $(this).children('.subnav-container').slideDown(500);
});

My fiddle:
http://jsfiddle.net/rzf7w69u/78/
I hope you guys can help me with my code.

A: There are multiple problems in the shared code.

*

*you are binding event in common class (shared by other elements too).

*Logic to manage slide up and slide down.
Here is your code, hope this will help you. 'Happy coding..'

Note: I did the code in your format, so this code can be improve more.

$(document).ready(function(){
$(".nav li.mega").hover(function(){
    $(this).addClass("hover");
    $(this).children(".subnav-container").addClass("hover");
},function(){
    $(this).removeClass("hover");
    $(this).children(".subnav-container").removeClass("hover");
});

var nav = $('.nav li.mega');
nav.children('.sibling').slideUp(0);
nav.click(function (e) {
    e.preventDefault();
    var ele=this;

    if( $(ele).children('.sibling').hasClass('open')){
      $(ele).children('.sibling').removeClass('open').slideUp(500);
    }
    else
    {
     if(nav.children('.open').length)
        {
        var child=nav.children('.open');
        $(child).removeClass('open').fadeOut(500,function(){         $(ele).children('.sibling').addClass('open').fadeIn(500); });
        }
        else
        {
        $(ele).children('.sibling').addClass('open').slideDown(500);
       }
   }
});
});
<!DOCTYPE html>

                        Nav 1

                                        Sub nav 1.1

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                        Sub nav 1.2

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                        Sub nav 1.3

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                        Nav 2

                                        Sub nav 2.1

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                        Sub nav 2.2

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                        Sub nav 2.3

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                                                        Sub Sub Nav
                                                        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna

                        Nav 3

                                        Sub nav 3.1

                                        Sub nav 3.2

                                        Sub nav 3.3


text:
Q: File upload not working correctly EDIT: HOW SHOULD I IMPLEMENT THE str_replace FUNCTION? IT ISNT WORKING. SEE THE CODE BELOW
I'm making a form in which people can upload images. The images are being resized so they fit in a image-carousel. I don't know how its possible, but when the image contains spaces or punctuation, the image will not be saved. When the image doesnt contains spaces it works fine. Can somebody please help me?
form part
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"
 enctype="multipart/form-data" name="form1" style="margin:0 auto; width:70%;
 color:black; font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
 font-size:16px; text-transform:none; font-weight:normal" >

afbeelding 1 (max 5Mb)

<input type="file" accept="image/*" name="afb1" id="afb1" style="float:right">

php part
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["afb1"]["name"]);
$extension1 = end($temp);
$newfilename1="afbeelding1.".$extension1;

if ((($_FILES["afb1"]["type"] == "image/gif")
|| ($_FILES["afb1"]["type"] == "image/jpeg")
|| ($_FILES["fb1"]["type"] == "image/jpg")
|| ($_FILES["afb1"]["type"] == "image/pjpeg")
|| ($_FILES["afb1"]["type"] == "image/x-png")
|| ($_FILES["afb1"]["type"] == "image/png"))
&& ($_FILES["afb1"]["size"] < 10000000)
&& in_array($extension1, $allowedExts)) {
if ($_FILES["afb1"]["error"] > 0) {
echo "Return Code: " . $_FILES["afb1"]["error"] . "
";
} else {
echo "Upload: " . $_FILES["afb1"]["name"] . "
";
echo "Type: " . $_FILES["afb1"]["type"] . "
";
echo "Size: " . ($_FILES["afb1"]["size"] / 1024) . " kB
";
echo "Temp file: " . $_FILES["afb1"]["tmp_name"] . "
";
if (file_exists('../upload/afbeeldingen/' . $newfilename1)) {
  echo $_FILES["afb1"]["name"] . " already exists. ";
} else {
    $images_orig = ImageCreateFromJPEG($_FILES["afb1"]["tmp_name"]);
    $photoX = ImagesX($images_orig);
    $photoY = ImagesY($images_orig);
    if ($photoY < $photoX*240/400) {
        $width=400; //*** Fix Width & Heigh (Autu caculate) ***//
        $size=GetimageSize($_FILES["afb1"]["tmp_name"]);
        $height=round($width*$size[1]/$size[0]);
        $images_fin = ImageCreateTrueColor($width, $height);
        ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
        ImageJPEG($images_fin,'../upload/afbeeldingen/'.$newfilename1);
        ImageDestroy($images_orig);
        ImageDestroy($images_fin);
    }
    else {
        $height=240; //*** Fix Width & Heigh (Autu caculate) ***//
        $size=GetimageSize($_FILES["afb1"]["tmp_name"]);
        $width=round($height*$size[0]/$size[1]);
        $images_fin = ImageCreateTrueColor(400, 240);
        ImageCopyResampled($images_fin, $images_orig, (400-$width)/2, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
        ImageJPEG($images_fin,'../upload/afbeeldingen/'.$newfilename1);
        ImageDestroy($images_orig);
        ImageDestroy($images_fin);
    }
}
}
} else {echo "Invalid file";}

VERSION 2:
like this? it isnt working
$nameafb1=$_FILES["afb1"]["name"];
$search = array(" ","_","(",")","!","@","#","$","%","^","&","*","-","+","=",";",":",">","'","/","<","?");
$nameafb1new = str_replace($search,"",$nameafb1);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $nameafb1nieuw);
$extension1 = end($temp);
$newfilename1="afbeelding1.".$extension1;

if ((($_FILES["afb1"]["type"] == "image/gif")
|| ($_FILES["afb1"]["type"] == "image/jpeg")
|| ($_FILES["fb1"]["type"] == "image/jpg")
|| ($_FILES["afb1"]["type"] == "image/pjpeg")
|| ($_FILES["afb1"]["type"] == "image/x-png")
|| ($_FILES["afb1"]["type"] == "image/png"))
&& ($_FILES["afb1"]["size"] < 10000000)
&& in_array($extension1, $allowedExts)) {
if ($_FILES["afb1"]["error"] > 0) {
echo "Return Code: " . $_FILES["afb1"]["error"] . "
";
} else {
echo "Upload: " . $nameafb1new . "
";
echo "Type: " . $_FILES["afb1"]["type"] . "
";
echo "Size: " . ($_FILES["afb1"]["size"] / 1024) . " kB
";
echo "Temp file: " . $_FILES["afb1"]["tmp_name"] . "
";
if (file_exists('../upload/afbeeldingen/' . $newfilename1)) {
  echo $_FILES["afb1"]["name"] . " already exists. ";
} else {
    $images_orig = ImageCreateFromJPEG($_FILES["afb1"]["tmp_name"]);
    $photoX = ImagesX($images_orig);
    $photoY = ImagesY($images_orig);
    if ($photoY < $photoX*240/400) {
        $width=400; //*** Fix Width & Heigh (Autu caculate) ***//
        $size=GetimageSize($_FILES["afb1"]["tmp_name"]);
        $height=round($width*$size[1]/$size[0]);
        $images_fin = ImageCreateTrueColor($width, $height);
        ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
            ImageJPEG($images_fin,'../upload/afbeeldingen/'.$newfilename1);
        ImageDestroy($images_orig);
        ImageDestroy($images_fin);
    }
    else {
        $height=240; //*** Fix Width & Heigh (Autu caculate) ***//
        $size=GetimageSize($_FILES["afb1"]["tmp_name"]);
        $width=round($height*$size[0]/$size[1]);
        $images_fin = ImageCreateTrueColor(400, 240);
        ImageCopyResampled($images_fin, $images_orig, (400-$width)/2, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);
        ImageJPEG($images_fin,'../upload/afbeeldingen/'.$newfilename1);
        ImageDestroy($images_orig);
        ImageDestroy($images_fin);
    }
}
}    } else {echo "Invalid file";}

A: There are a few ways to accomplish this.
You can use PHP's trim() function.
$nameafb1=trim($_FILES["afb1"]["name"]);

This will "trim" unwanted spaces from the beginning and/or end.
or PHP's str_replace() function which has the ability to replace all spaces found:
$string = " hello world ";
$string = str_replace(' ', '', $string);
 echo $string;

so in your case that would be:
$nameafb1=$_FILES["afb1"]["name"];

$nameafb1 = str_replace(' ', '', $nameafb1);

You can also replace spaces using underscores:
$nameafb1=$_FILES["afb1"]["name"];

$nameafb1 = str_replace(' ', '_', $nameafb1);

Another option is using the preg_replace() function:
$nameafb1 = preg_replace('/\s+/', '_', $nameafb1);

which will replace the spaces to underscores. You can delete the underscore in '_' and change it to '' if you don't want them.


text:
Q: Display user specific data from MySql in Android Studio I am currently building an app in which students from an university/school log in and see their marks and other specific info about themselves. I would like to know if it's possible to retrieve data from a table just for the user that logged in and display it, and how exactly could I do that?
Eg. If user A logs in and he wants to see his marks, the he would just go to the marks activity and that would display his marks
LoginActivity.java
public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

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

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtName = (TextView) findViewById(R.id.name);
        txtEmail = (TextView) findViewById(R.id.email);
        btnLogout = (Button) findViewById(R.id.btnLogout);

        // SqLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // session manager
        session = new SessionManager(getApplicationContext());

        if (!session.isLoggedIn()) {
            logoutUser();
        }

        // Fetching user details from sqlite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        String email = user.get("email");

        // Displaying the user details on the screen
        txtName.setText(name);
        txtEmail.setText(email);

        // Logout button click event
        btnLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                logoutUser();
            }
        });
    }

    /**
     * Logging out the user. Will set isLoggedIn flag to false in shared
     * preferences Clears the user data from sqlite users table
     * */
    private void logoutUser() {
        session.setLogin(false);

        db.deleteUsers();

        // Launching the login activity
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}


text:
Q: How to consume Trino data with GraphQL We have a dataplatform built around Trino and Privacera and it is working well. It is possible to query data from dozens of sources through trino and authorization with Privacera works like a charm.
Then we have a new requirement stating that they want to consume data from Trino with GraphQL. We really don't want to write all the GraphQL schemas and resolvers by hand and were hoping to be able to use Hasura. But Hasura can only auto generate the schemas/resolvers for Postgres and a few others. Trino is not on the map.
We were thinking of mirroring the data that is exposable to the GraphQL users in a PostgresQL database, but that would defeat the purpose of Trino.
I am out of ideas and was hoping to hear if someone would expose the data to the consumers with GraphQL in some other way.
So, any ideas of how to expose the data queryable by Trino through some automatic tooling with GraphQL?


text:
Q: Sign certificate in PKCS#11 To sign certificate in OpenSSL I use X509_sign() function by feeding it with a request (as X509_REQ*), a signing key and a digest.
Now I have my signing key stored in HSM, so I can't extract it to sign the certificate. Unfortunately PKCS#11 does not provide an equivalent to X509_sign(). All it has is C_Sign() / C_SignUpdate() / C_SignFinal() family of functions which operate on raw data, not on certificates.
Can someone help me with sample C/C++ code how to use PKCS#11 to sign a certificate created with OpenSSL?

A: The code below signs the given X509* structure within HSM. Error handling is omitted for the sake of clarity.
void signCertInHsm(X509* x509, unsigned long pkcs11SigningAlgo, CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE p11session, CK_OBJECT_HANDLE pkcs11PrivKeyHandle)
{
    x509->cert_info->enc.modified = 1;

    // set signature algorithm in the certificate
    if (x509->cert_info->signature)
    {
        const int signingAlgoNid = pkcs11SignatureAlgorithmToNid(pkcs11SigningAlgo);
        X509_ALGOR_set0(x509->cert_info->signature, OBJ_nid2obj(signingAlgoNid), V_ASN1_NULL, NULL);
    }
    if (x509->sig_alg)
    {
        const int signingAlgoNid = pkcs11SignatureAlgorithmToNid(pkcs11SigningAlgo);
        X509_ALGOR_set0(x509->sig_alg, OBJ_nid2obj(signingAlgoNid), V_ASN1_NULL, NULL);
    }

    // DER-encode certificate
    unsigned char *certDerBuf = NULL;
    const size_t certDerLen = ASN1_item_i2d((ASN1_VALUE*)x509->cert_info, &certDerBuf, ASN1_ITEM_rptr(X509_CINF));

    CK_MECHANISM mechanism = { pkcs11SigningAlgo, NULL_PTR, 0 };
    p11->C_SignInit(p11session, &mechanism, pkcs11PrivKeyHandle);

    // determine signature size
    CK_ULONG signatureSize = 0;
    p11->C_Sign(p11session, certDerBuf, certDerLen, NULL, &signatureSize);

    // sign
    if (x509->signature->data)
        OPENSSL_free(x509->signature->data);
    x509->signature->data = (unsigned char*)OPENSSL_malloc(signatureSize);
    x509->signature->length = signatureSize;
    p11->C_Sign(p11session, certDerBuf, certDerLen, x509->signature->data, &signatureSize);

    x509->signature->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07);
    x509->signature->flags|=ASN1_STRING_FLAG_BITS_LEFT;

    OPENSSL_free(certDerBuf);
}

int pkcs11SignatureAlgorithmToNid(unsigned long algo)
{
    switch(algo)
    {
    case CKM_SHA1_RSA_PKCS: return NID_sha1WithRSAEncryption;
    case CKM_SHA256_RSA_PKCS: return NID_sha256WithRSAEncryption;
    //... add more mappings that your app supports
    default: throw std::invalid_argument("Not supported signature algorithm");
    }
}

A: The another way to sign a certificate by HSM is by using the X509_sign() function, but implementing your own signing callback.
An example can be found in https://github.com/OpenSC/libp11/blob/master/src/p11_pkey.c
pkcs11_pkey_method_rsa() - is how to add your own callback
pkcs11_try_pkey_rsa_sign(...) - is how to implement the signing (RSA)


text:
Q: the time taken to read a file I have a question. How long time does it takes to read a 2 mb file, which is fragmented in 2?
If the rotational delay is 4300 rpm
And the seektime is 10 ms
the transfer time is 10 mb/s
and the controller overhead is 0,5 ms.
My calculation is:
2*(10 ms + 7 ms (<-rotational delay) + 0,5 ms + 200 ms (<-transfer time))

Is this the right answer or have I done something wrong?

A:
Disk Access Time = Seek time +
  Rotational Latency + Transfer time +
  Controller Time + Queueing Delay(if
  any)

So, get back to your book and find the correct answer.


text:
Q: Image server path ASP.NET Including controller and method I am having a problem deleting an image in my ASP.NET MVC 5 application.
I am creating a user management module of an application which requires images/photos of the staff uploaded. However, since the profile should be editable, the image should be made possible to be deleted. But when I try to delete the image, I find it difficult locating the correct path of the image. When I use
var fileToDelete = Path.Combine(Server.MapPath("~Content/photos/people/"),updatedStaff.Photo);
                            System.IO.File.Delete(fileToDelete);
or
`var fileToDelete = Server.MapPath("~Content/photos/people/"+updatedStaff.Photo);
                        System.IO.File.Delete(fileToDelete);`

The path returned for the image is wrong in that, it contains the controller and method in the path and so I cannot delete the image.
This is the error message I get:
Could not find a part of the path 'C:\Users\Josh\documents\visual studio 2015\Projects\EduPlus\EduPlus\staffmembers\edit\~Content\photos\people\de1e1cf0-d.jpg'
"staffmembers" is the controller and "edit" is the method
Please I will appreciate any assistance to figure out the problem.
Thank you

A: ~/ is what you need to use before Content, not just ~ .
This should work perfectly fine.
var fileToDelete = Path.Combine(Server.MapPath("~/Content/photos/people"),
                                                                     updatedStaff.Photo);


text:
Q: How to fix score addition failure I'm making a quiz. The user has 3 tries to guess the answer to the question.
My problem is that the scoring system isn't working properly. If the user guesses the answer the first time it adds 3 points, which works. However, the program adds 0 points if the user guesses the second time when it's supposed to add 1 point.
I've tried asking people around me and swapping the if statements, so that the possibility of the program assuming the score is lost.
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while counter < 3 and songnameguess != randomsong :
        songnameguess = input("Nope! Try again!")
        counter = counter + 1
if songnameguess == randomsong:
    print ("Well done!")
    answer = input("Do you want to continue playing?")
    print (counter)
    if counter == 2:
        score == score + 1
        print (score)
    elif counter == 1:
        score = score + 3
        print (score)

When the user guesses the answer correctly the first time, they are supposed to have 3 points added to their score, and when the user guesses the answer correctly the second time, they are supposed to have 1 point added to their score. If the user does not guess the score in three tries, the game ends.

A: This line of code is wrong
    score == score + 1

== should not be used but = should be used
Hope it helps


text:
Q: QueryPerformanceCounter returning negative number Hey im trying to count how long the function takes to execute
I am doing it like this:
Timer.cpp
long long int Timer :: clock1()
{
    QueryPerformanceCounter((LARGE_INTEGER*)&time1);
    return time1;
}
long long int Timer :: clock2()
{
    QueryPerformanceCounter((LARGE_INTEGER*)&time2);
    return time2;
}

main.cpp
#include "Timer.h"  //To allow the use of the timer class.

Timer query;

void print()
{
    query.clock1();
    //Loop through the elements in the array.
    for(int index = 0; index < num_elements; index++)
    {
        //Print out the array index and the arrays elements.
        cout <<"Index: " << index << "\tElement: " << m_array[index]<<endl;
    }
    //Prints out the number of elements and the size of the array.
    cout<< "\nNumber of elements: " << num_elements;
    cout<< "\nSize of the array: " << size << "\n";
    query.clock2();
    cout << "\nTime Taken : " << query.time1 - query.time2;
}

Can anyone tell me if i am doing this correctly?

A: You are substracting ending time from starting time.
cout << "\nTime Taken : " << query.time1 - query.time2;

should be
cout << "\nTime Taken : " << query.time2 - query.time1

A: Let's say I start something at 10 seconds and it finishes at 30 seconds. How long did it take? 20 seconds. To get that, we would do 30 - 10; that is, the second time subtract the first time.
So perhaps you want:
cout << "\nTime Taken : " << (query.time2 - query.time1);


text:
Q: How can I implement Bulk insert in ASP.NET Core 1.0? I want to import the data from database in .csv format and want to export .csv into my SQL server/Oracle database. I am using ASP.NET Core RC 1 at this moment. I looked into SQLBulkCopy class but the issue is that it is not ported to ASP.NET Core.
Can someone tell me how can I do it or is there any other compatible nuget package available (with ASP.NET Core)?

A:
Microsoft has added SqlBulkCopy to .NET Core, so you can bring it in as part of the System.Data.SqlClient NuGet package. I opted to use FastMember by @MarcGravell to handle the work of mapping my data, but you don't have to.
FastMember will take a collection of parameters, and a collection of objects, and pull the values off your objects that map to your collection of parameters. Really simplifies the code.
private async Task OutputPerformanceDataToStorage(List<PerformanceData> dataToSave)
{
    var storageParameters = new[]
        {
            nameof(PerformanceData.PerformanceId),
            nameof(PerformanceData.IPAddress),
            nameof(PerformanceData.ControllerName),
            nameof(PerformanceData.ActionName),
            nameof(PerformanceData.ActionParameters),
            nameof(PerformanceData.ViewPath),
            nameof(PerformanceData.TotalRequestTimeInMilliseconds),
            nameof(PerformanceData.RequestStartedTimestamp),
            nameof(PerformanceData.RequestEndedTimestamp),
            nameof(PerformanceData.CreatedDateTime),
        };

    var sqlCopy = new SqlBulkCopy(this.connectionString, SqlBulkCopyOptions.Default);
    sqlCopy.DestinationTableName = "[Performance]";

    using (var reader = ObjectReader.Create(dataToSave, storageParameters))
    {
        await sqlCopy.WriteToServerAsync(reader);
    }
}

internal class PerformanceData
{
    public Guid PerformanceId;
    public double TotalRequestTimeInMilliseconds;
    public long RequestStartedTimestamp;
    public long RequestEndedTimestamp;
    public string IPAddress;
    public string ControllerName;
    public string ActionName;
    public string ViewPath;
    public string ActionParameters;
    public List<string> ActionParametersList;
    public DateTime CreatedDateTime;
}

A: .NET Standard 2.0 now supports many of the .NET framework libraries which means that SqlBulkCopy class can be used with ASP.NET Core. Dataset, Datatables and SQLBulkCopy will do the job for bulk insertion. Find more details about .NETStandard 2.0 here.


text:
Q: How to implement bearer token authentication in MVC4/ WebAi 2 Can somebody give me a sample code or a guidance on  how to implement HostAuthenticationFilter in MVC4/WebApi 2 project where I have implemented Cookie based authentication in MVC4 project and then I added an Area called Api where I have exposed EDM using WebApi2 and OData V3 but I need to implement OAuth 2 token i.e. bearer based authentication in order to access api controller. In addition to this, I need login controller in my api as clients are Native Mobile Apps (iOS and Android users). Thank you.

A: I was reading all the related articles online throughout the day and finally found the similar case here and then I decided to follow this sample.
Finally, Its better to separate the API and Frontend MVC4 in different projects in order to avoid the complexity of Cookies and Token based security and other issues.


text:
Q: Creating lists from elements in a bigger list I have a list whose size is a multiple of 16. What I want to do is go through the list and get 16 elements and create a list from those values, and then store those values somewhere. After that I can either ignore them or remove  them from the list, and continue this process until the bigger list is empty. What I was trying to do was to go through the list, and keep a counter of some sort to keep track of the number of elements that have been appended to the list. However, I have been stuck from there. Any ideas on how to accomplish on what I am trying to do? Any ideas would be greatly appreciated.
lst = [[1, 4, 0], [2, 4, 0], [3, 4, 0], [4, 4, 0], [1, 3, 0], [2, 3, 0], [3, 3, 0], [4, 3, 0], [1, 2, 0], [2, 2, 0], [3, 2, 0], [4, 2, 0], [1, 1, 0], [2, 1, 0], [3, 1, 0], [4, 1, 0],[1, 4, 0], [2, 4, 0], [3, 4, 0], [4, 4, 0], [1, 3, 0], [2, 3, 0], [3, 3, 0], [4, 3, 0], [1, 2, 0], [2, 2, 0], [3, 2, 0], [4, 2, 0], [1, 1, 0], [2, 1, 0], [3, 1, 0], [4, 1, 0]]

A: If I understand you correctly, you start with a list of size n, where n % 16 == 0. You want to end with n/16 lists of size 16. You can accomplish this pretty easily with a double for loop. The outer loop should go for n/16 iterations. the inner loop should go for 16 iterations. The outer loop creates a new list with each iteration. the inner loop takes elements from the original list and appends them to the newly created list.

A: Thank you for taking the time to respond to my question. After clicking on random links on the right hand side I came to answer that did exactly what I needed to happen.
Here is the solution to my problem:
[input[i:i+n] for i in range(0, len(input), n)]

The solution above goes through input and creates a list of size n.


text:
Q: Chef Test Kitchen: How to verify Jenkins is running in sandbox I am currently using the Jenkins Supermarket cookbook to create a Jenkins instance. I am using the Java_se cookbook to configure Java as a prerequisite of installing Jenkins. Prior to configuring a managed node with the cookbook, I am using Test Kitchen to verify that the provisioning is successful before configuring my managed node.
Once my Test Kitchen instances are up and running, I am verifying the Java installation using the following command:
kitchen exec -c 'java -version'

which yields the version of Java on the instance if the java configuration has been successful.
My question is, what are some good ways to verify that Jenkins is up and running on the Test Kitchen sandbox instance? I'd like to check the url; for example http://localhost:8080. There are also some additional checks I'd like to do (plugins that are installed as part of the recipe, as well as security that is enabled at the end of configuring the instance).
Does anybody have any good ideas / leads as to how to verify my Jenkins instance is configured correctly when using a Test Kitchen sandbox environment? Thanks everybody for any ideas that may have!

A: If you use busser-serverspec, you just write the tests as per normal locally, usually using Net::HTTP.get('http://localhost:8080/whatever').
If you use kitchen-inspec, you need to be a little more roundabout and use something like describe command('curl http://localhost:8080/whatever') and work with it like a normal command resource.


text:
Q: Swift iOS: fatal error when dismissing alert controller while keyboard is up So, I've got a view controller with a number of text fields on it. The first two text fields need text entered into them before submitting. I check the first two text fields and display an alert controller in case they're empty.
    let alertController = UIAlertController(title: "Error", message:
                "Please enter some text.", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)

This works fine, as long as the keyboard is dismissed before trying to submit the form. If the keyboard is still showing however, the app crashes with fatal 'error: unexpectedly found nil while unwrapping an Optional value'
What is happening here?

A: Just solved this myself by adding view.endEditing(true) before displaying the alert controller. Would still like to know why it was crashing in the first place.


text:
Q: About the entry point of PE in Windows Is it always at the lowest address of code section?

A: No, not necessarily.  The PE entry point is defined in the IMAGE_OPTIONAL_HEADER structure, in the AddressOfEntryPoint field:

A pointer to the entry point function, relative to the image base address. For executable files, this is the starting address. For device drivers, this is the address of the initialization function. The entry point function is optional for DLLs. When no entry point is present, this member is zero.

A linker can set this to be whatever it wants to be, as long as its a valid relative virtual offset into the PE.  Some compilers and linkers might have the convention of putting the entry point at the beginning of the text/code section, but there's no OS or PE format requirement for it.


text:
Q: QT4: How to get access to an object what is on mainwidow from an other class? If Im in mainwindow.cpp then i can get every object on it with:
this->ui->textBox ...

What if there is another class (myclass2.cpp) and I would like to get the value of one the textBoxes. But they are on my mainwindow. I cant use this->ui->textBox
Whats the way to get access to the objects?
Thank You

A: In general, this is not a problem specific to Qt.  There are several ways you can do this:

*

*Provide a method on mainwindow that encapsulates what you want, and call that from myclass2.
// In mainwindow.cpp:
QString mainwindow::valueOfTheTextEditYouAreInterestedIn() const
{
     return ui->textBox->toPlainText();
}

This has lots of benefits: clean design, easy to change later, and highly self-documenting, just to name a few.  For this to work, your myclass2 object will still need a pointer to the main window, though.  Then you would call it like this:
// In myclass2.cpp:
{
    // we're in some function of myclass2
    QString value = theMainWindow->valueOfTheTextEditYouAreInterestedIn();

    // Use the value...
}

*Provide an accessor for the text edit.  This is not such a good idea, because then myclass2 can alter the text edit without mainwindow knowing about it.  However, it would look like:
QTextEdit *getTheInterestingTextEdit()
{
     return ui->textBox;
}

This can be made more acceptable by returning a constant pointer, so that myclass2 will be able to read, but not modify, the values of the text edit:
const QTextEdit *getTheInterestingTextEdit() const
{
     return ui->textBox;
}

Qt provides yet another way to do the same thing, but you don't have to write your own method for it:
// In myclass2.cpp:
QTextEdit *textBox = theMainWindow->findChild<QTextEdit *>("textBox");

where mainwindow is a pointer to the main window object that myclass2 will need to obtain somehow, and "textBox" is the Qt object name you gave the interesting text box in Designer.  And it will only work if the text edit object is a child widget of the main window object, which it should be in this case.  You may run into trouble if you rely on this technique in general, though.

*You could always make myclass2 a friend of mainwindow.  This is so much not recommended, that I'm not going to post some code, though. :-)


text:
Q: .replace method doesn't work in Python even if assigned to a new variable I have read some posts before and tried to fix this myself but all of them mentioned that the .replace method in Python does not actually replace the variable but instead creates a new string with the changes made. What you then have to do is assign this "new" string to a variable to store it or to my understanding you can assign the result to the original variable to overwrite it. Even after those steps however the .replace method still refuses to work.
Here's the code that I am having problem with :
url = input("Stream urls: ")
urls = url.split("," or "/" or " ")

# Find urls in the provided string
def find_url():
    findall(r'(https?://[^\s]+)', url)

# Format and clear urls
def format_url():
    for url in urls:
        if "https://www." in url:
            url = url.replace("https://www.", "https://")
        elif "www." in url:
            url = url.replace("www.", "https://")
        elif "http://" in url:
            url = url.replace("http://", "https://")

As seen in the code a user is asked to put in links which are then converted to a list with a possible separator of each link with ', / " "'. This part and the next part are provided only for goal reference and there doesn't seem to be any issue with them. The problematic part is te format_url() function.
At first I thought that the replace method logically cannot be used on lists so I made a for loop which loops throught every single link in the links list. This to my understanding should result in the .replace method only obtaining 1 record at a time which should make it work.
I also didn't forget to call the methods with :
find_url()
format_url()
url_source()

A: I guess it's more helpful to post an answer, rather than just comments. Hopefully this should illustrate the issue:
strings = ["hello", "yellow", "jello"]

for current_string in strings:
    current_string = current_string.replace("e", "3")
    print(f"current_string is {current_string}, and strings is {strings}")

Output:
current_string is h3llo, and strings is ['hello', 'yellow', 'jello']
current_string is y3llow, and strings is ['hello', 'yellow', 'jello']
current_string is j3llo, and strings is ['hello', 'yellow', 'jello']
>>>

As you can see, current_string does not behave like a handle to each string in strings. It's just a copy. Mutating or re-binding the copy has no effect on the strings from which it was derived.
Here's one way you can apply the changes:
strings = ["hello", "yellow", "jello"]

for index, current_string in enumerate(strings):
    strings[index] = current_string.replace("e", "3")

print(strings)

Output:
['h3llo', 'y3llow', 'j3llo']
>>>

While we're at it, take a look at this:
>>> "," or "/" or " "
','
>>>

As mentioned in my previous comment, such a boolean expression (chained ors) will evaluate to the first truthy string it comes across due to short circuiting, from left to right. A string is considered "truthy" if it is not empty. So, the first non-empty string is ",". Therefore, you only split on ",".


text:
Q: integrate wordnet with solr7.5.0 I am beginner in solr7.5.0 and I don't know each and every modules of it. As I'm building question answer system I want to integrate wordnet so I can get better query responses. I googled it and found some methods and previous question but I'm really confused on how to do in solr version 7.5.0 step by step.
Edit: solr7.5.0 having WordnetSynonymParser class, So if anyone worked on same please guide me how I can use this class or is there another way to do it? and can I use python to do it?
thanks in advance.

A: This article is very useful for this question, and the integration of wordnet can be done by, there are WordNet prolog file('wn_s.pl') which has synsets, we can convert it to synonyms.txt which can be consumable by Solr. So, to convert wn_s.pl file we can use Syns2Syms.java. It generates Synonyms.txt which we can index to solr.
But WordNet expansion will only yield marginal gains in relevance if it is domain specific search, so simply creating your own synonyms list based on the common tokens in your index will give more relevance.


text:
Q: How to get input on button click with reactstrap I have an input field and when the button is clicked I would like to store the input to a variable and output it to console. Here is my code:
function InputDD() {
       const [inputValue, setInputValue] = useState('');
       const onChangeHandler = event => {
           setInputValue(event.target.value);
       };
       //console.log(inputValue) <- Not working

       return(

       <Form>
           <FormGroup>
                <Input type="lk" name="inputK" id="inputK" className="ink" value={inputValue} onChange={onChangeHandler} />
           </FormGroup>
           <Button size="sm" className="nextbtn">Lets roll</Button>

       </Form>

       )
}

export default InputDD;

Currently, whenever an input is entered, the keys are output in console like in this image:

I do not want this and only want the whole text that is input stored to a variable and printed to console when the button is clicked.

A:     function InputDD() {
           const [inputValue, setInputValue] = useState('');
           const onChangeHandler = event => {
               setInputValue(event.target.value);
           };
           const handleSubmit = (e) => {
              e.preventDefault()
              console.log(inputValue) //working
           }

           return(

           <Form onSubmit={(e) => handleSubmit(e)}>
               <FormGroup>
                    <Input
type="lk"
name="inputK"
id="inputK"
className="ink"
value={inputValue}
onChange={(e) => onChangeHandler(e)}
/>
               </FormGroup>
               <Button size="sm" className="nextbtn">
Lets roll
</Button>
    <Button size="sm" className="nextbtn" type="submit">
Lets roll
</Button>
           </Form>

           )
    }

    export default InputDD;


text:
Q: Cloud Firestore - Access Field for Realtime Updates I am trying to access a field labeled vote_count via Cloud Firestore realtime updates.
Below is my data structure:

Previously, under Firebase Realtime Database, I would .addValueEventListener() and drill down to the "answer." However, with Cloud Firestore, it is a bit more complex.

    mStoreSelectedPollRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(final DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
            if (e != null){
                Log.v("LISTEN", "LISTEN_FAILED");
                return;
            }
            if (documentSnapshot != null){
                Log.v("Current Data", String.valueOf(documentSnapshot.getData()));
                mStoreSelectedPollRef.collection(ANSWERS_LABEL).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        updatePollResultAnswersDynamically(task.getResult().size(), documentSnapshot);
                    }
                });
            } else {
                Log.v("Current Data", "Current Data Nulll");
            }
        }
    });

Right now, I am adding a call to .get() within my Snapshot Listener, which seems to be inefficient. I was curious how I would access the:

*

*Total number of answer Documents.

*Each individual answer

A: Given this snippet:
mStoreSelectedPollRef.collection(ANSWERS_LABEL).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        updatePollResultAnswersDynamically(task.getResult().size(), documentSnapshot);
    }
});

You can get the total number of answer documents with:
task.getResult().size()

Since you already have this code, I'm not really sure what you're asking. If you're asking if there is a way to get the count without getting the documents, look here: https://stackoverflow.com/a/46555026
To access the individual answer documents, you loop over the query snapshot:
for (DocumentSnapshot document : task.getResult()) {
    Log.d(TAG, document.getId() + " => " + document.getData());
}


text:
Q: Javascript setTimeout function with 'this'
Possible Duplicate:
setTimeout and "this" in JavaScript

I am trying to put a timeout on an Object. With some test code (see below) I want to decrease the timerPos until it reaches 0. When I use the code below the first time timerInc() is called by startTimer(), it will reach 3 (as expected). When TimerInc() is called by the timeout i will receive 'undefined' for the timerPos variable. What am I doing wrong?
function start(){
var alert = new Alert(3);
alert.startTimer();

}
function Alert(timer) {
    this.timerMinutes = timer;
    this.timerPos = 0;

    this.startTimer = function() {
        this.timerPos = this.timerMinutes+1;
        this.timerInc();
    };

    this.timerInc = function() {
        if (this.timerPos > 0){
            this.timerPos--;
                    // first time this function gets called timerPos is 3
                    // the second time when its called by the timeout it
                    // will be 'undefined'
            setTimeout(this.timerInc,1000);
        }
    };
}

(using this.timerInc() in the timeout instead of this.timerInc does not work for me, neither does using quotes)

A: You need to bind the "this" variable to another one that you use explicitly since the value of "this" changes based on who is calling the function!
function Alert(timer) {
  var that = this; // Store this Alert instance as "that".
  this.timerMinutes = timer;
  this.timerPos = 0;

  // ...
  this.timerInc = function() {
    // Use the Alert instance "that", not whatever is bound to "this" at runtime.
    if (that.timerPos > 0){
      that.timerPos--;
      setTimeout(that.timerInc, 1000);
    }
  };
}

The issue is that the setTimeout() function will call its function argument from global scope, not the scope of the enclosing object at the time it is registered.  So in global scope the "this" variable is bound to the "global" object (likely the browser window).
You can verify like so:
setTimeout(function(){alert(this);}, 500); // => alerts "[object DOMWindow]"

A: First of all you should use prototype to declare the methods of your class Alert. And changing the scope of the function you're calling is gonna do the job:
function start(){
var alert = new Alert(3);
alert.startTimer();

}
function Alert(timer) {
    this.timerMinutes = timer;
    this.timerPos = 0;
}

Alert.prototype.startTimer = function() {
        this.timerPos = this.timerMinutes+1;
        this.timerInc();
    };

Alert.prototype.timerInc = function() {
    if (this.timerPos > 0){
        this.timerPos--;
        console.log(this.timerPos);
        setTimeout(function(_this){_this.timerInc()},1000,this);
    }
};

DEMO: http://jsfiddle.net/kmendes/HNYKa/1/


text:
Q: how do i access a public method of a default class outside the package I have a class with no modifier(default), which has a public method called mymeth. I know I could access the method when I am within the package. However I would like to access the method when I am outside the package. does anyone has an Idea on how it could be done. theoretically I think it should be possible since public method means access by the world. here is the example of my class and method:
class myclass{

public void mymeth(int i,int b){

.....
  }

}

A: set myclass class to be public.
**FYI, Classes in Java start from upper Case letter

A: Directly you cannot. 'public' makes everything visible. But if you can't see the class, it's difficult to call anything. However,
You can extend the default class with a public class, eventually myMeth is exposed.
PubClass.java
package p1;

class DefClass{
    public void myMeth(){
        System.out.println("from myMeth!");
    }
}

public class PubClass extends DefClass{
    public PubClass(){
        super();
    }
}

MainClass.java
package p2;

class MainClass {

    public static void main(String[] args) {
        p1.PubClass pub = new p1.PubClass();

        pub.myMeth();
    }

}

output:
from myMeth!

A real practical use for this would be, overriding a public known method in that hidden class. You can implement a public method in a hidden class, so the world can call your public method (public implementation rather) without the class being exposed. For example the public method of the Object class is overridden here by DefClass:
PubClass.java
package p1;

class DefClass{
    public String toString(){
        return "DefClass here. Trying to explain a concept.";
    }
}

public class PubClass extends DefClass{
    public PubClass(){
        super();
    }
}

MainClass.java
package p2;

class MainClass {

    public static void main(String[] args) {
        p1.PubClass pub = new p1.PubClass();
        System.out.println(pub.toString());
    }
}

output:
DefClass here. Trying to explain a concept.

A: Set myclass as public then put it in the build path of the class you need to use myclass.

A: public interface SomeInterface{
   public void mymeth();
}

class MyClass implements SomeInterface{

   public void mymeth(){

   }
}

//is in the same package as MyClass
public MyClassFactory{
   public SomeInterface create(/*parameters*/){
       //create instance from parameters
       //For your case
       MyClass instanceOfAnyClassThatImplementsSomeInterface = new MyClass(/*pass the parameters*/);
       return instanceOfAnyClassThatImplementsSomeInterface;
   }
}

One of the ways is already defined in answers but If you want to restrict the public access of the class then you can create an interface and access the method through it.

A: In your code, myclass has the default (package-level) access modifier. It should be declared using the public access modifier so that it is accessible outside its package. For details, read more about Controlling Access in Java.
As a side note, the Java standards require you to capitalize each word in the class name, so you should use MyClass. I recommend you the Java Conventions document.

A: Consider making another public class MyChild with the same package name as MyClass and expose the method from MyChild class
public class MyChild extends MyClass {

  public void myTestMethod(){
     super.myTestMethod
   }

}
Now in your class where you want to use the method, simply use the instance of MyChild class
MyChild m = new MyChild();

m.myTestMethod();

Cheers :)


text:
Q: Create view for a child-master relationship I have an entity called Entity, (lol).
        public class Entidad
    {
        [Key]
        public int Id { get; set; }
        public string Nombre { get; set; }

        public virtual ICollection<Propiedad> Propiedades { get; set; }
}

I also have an entity called Properties
 public class Propiedad
    {
        [Key]
        public int Id { get; set; }

        public virtual Entidad Entidad { get; set; }

        public string Codigo { get; set; }
        public string Nombre { get; set; }
        public string TipoDeDatos { get; set; }
    }

My Create view with the automated scaffolding gets rendered like this
http://screencast.com/t/aNU4tEH8EA1
However, I should be able to select the Entity from a dropdown list.
this is the automatically generated view
@model Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad

@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}

Create

                @Html.ActionLink("List", "Index")

                Create

            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-primary"})

Create Propiedad

                @using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.Codigo, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Codigo)
                @Html.ValidationMessageFor(model => model.Codigo)

            @Html.LabelFor(model => model.Nombre, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Nombre)
                @Html.ValidationMessageFor(model => model.Nombre)

            @Html.LabelFor(model => model.TipoDeDatos, new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.TipoDeDatos)
                @Html.ValidationMessageFor(model => model.TipoDeDatos)

                <input type="submit" value="Create" class="btn btn-primary" />
                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-white"})

}

Questions is how can I add the dropdown and make it fill the values from the entities?

A: You can't do that automatically.
You'll need to add a DropDownList to your View and add every entity you want to be selectable to this dropdown.
On the post, query for the entity, and then create Add the properties to it.
Also, check your controller, the default behavior for MVC is to create a child entity controller receiving the parent (in this case 'Entidad') id, make it receive only the model for semantics since you're not 'Entidad' specific in this case.


text:
Q: What file is my sql table stored in? I have a table in SQL Server 2008 R2. I want to know what file the data is being stored on. I know what filegroup the table is stored on. But I want to know which file it's on.
Or is that not possible? I guess the whole idea of filegroups is to have one table/index span multiple physical drives, so maybe the table is split between the two files in the filegroup.
Is that right?

A: For all intents and purposes, you should assume that your table's data is spread across all of the files in its filegroup. You can probably manually inspect all of the pages using undocumented stuff like DBCC PAGE, but I fail to see the point. If you find even one page in each file, what are you going to do then? If you go through and eliminate one of the files as not having any rows, by the time you do anything about it, it might. The whole point of pointing a table or index or partition at a multi-file filegroup is to spread the data across those files, not create a hot spot in any single file.


text:
Q: How can i use LightStatusBar on Android M with a custom action bar? While designing the User Interface, I wanted to use the black statusbar icons mode that's available for Android M and above (Material.LightStatusBar), but there's a problem.
I have created a main activity with 3 full screen Fragments using ViewPager, and I'm using an improvised ActionBar (based on relative layout with a white background, and a TextView as the title, so when I scroll the pager and change the fragments the ActionBar scrolls too) and I want to change the status bar into dark icons so it looks better on a white background.
I tried to change my app's style into Material.LightStatusBar, but I don't want to use the standard actionbar/toolbar since it can't be scrolled with my Viewpager.
Does anybody knows how can I achieve that?


text:
Q: How to convert a Vec> into a string I am new to Rust, and I am struggling with a simple task. I'd like to convert a matrix into a string, with the fields separated by tabs. I think this is possible by using the map function or something similar, but right now whatever I try gives me an error.
This is what I have, and I'd like to convert the col part into function, which returns a tab separated string, which I can print.
In Python this is something like row.join("\t"). Is there something similar in Rust?
fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec.iter() {
        for col in row.iter() {
           print!("\t{:?}",col);
        }
        println!("\n");
    }
}

A: There is indeed a join in the standard library, but it's not super useful (often additional allocation is required). But you can see a solution here:
fn print_matrix(vec: &Vec<Vec<f64>>) {
    for row in vec {
        let cols_str: Vec<_> = row.iter().map(ToString::to_string).collect();
        let line = cols_str.join("\t");
        println!("{}", line);
    }
}

The problem is that this join works with slices and not with iterators. We have to convert all elements into a string first, collect the result in a new vector and can use join then.
The crate itertools defines a join method for iterators and can be applied like so:
for row in vec {
    let line = row.iter().join("\t");
    println!("{}", line);
}

And to avoid using any of the named functionality, you can of course do it manually:
for row in vec {
    if let Some(first) = row.get(0) {
        print!("{}", first);
    }
    for col in row.iter().skip(1) {
        print!("\t{}", col);
    }
    println!("");
}

A: Besides join from itertools you could always use fold on iterator (which is really useful), like this:
row.iter().fold("", |tab, col| { print!("{}{:?}", tab, col); "\t" });


text:
Q: Overloading + to support tuples I'd like to be able to write something like this in python:
a = (1, 2)
b = (3, 4)
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)

I realize that you can overload operators to work with custom classes, but is there a way to overload operators to work with pairs?
Of course, such solutions as
c = tuple([x+y for x, y in zip(a, b)])

do work, but, let aside performance, they aren't quite as pretty as overloading the + operator.
One can of course define add and mul functions such as
def add((x1, y1), (x2, y2)):
    return (x1 + x2, y1 + y2)

def mul(a, (x, y)):
    return (a * x, a * y)

but still being able to write q * b + r instead of add(times(q, b), r) would be nicer.
Ideas?
EDIT: On a side note, I realize that since + currently maps to tuple concatenation, it might be unwise to redefine it, even if it's possible. The question still holds for - for example =)

A: In contrast to Ruby, you can't change the behaviour of built-in types in Python.  All you can do is create a new type derived from a built-in type.  Literals will still create the built-in type, though.
Probably the best you can get is
class T(tuple):
    def __add__(self, other):
        return T(x + y for x, y in zip(self, other))
    def __rmul__(self, other):
        return T(other * x for x in self)
a = T((1, 2))
b = T((3, 4))
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)

A: You can inherit a class from tuple and overload its __add__ method. Here's a very simplistic example:
class mytuple(tuple):
    def __add__(self, other):
        assert len(self) == len(other)
        return tuple([x + y for x, y in zip(self, other)])

mt = mytuple((5, 6))
print mt + (2, 3)  # prints (7, 9)

I wouldn't recommend this approach though, because tuples weren't really designed for this purpose. If you want to perform numeric computations, just use numpy.

A: You cannot modify types defined in C, so you would need to create all new types for this. Or you could just use NumPy, which already has types that support this.

A: Using python complex numbers is definitely one way to do it, if not extremely pretty.
a = 1 + 2j
b = 3 + 4j
c = a + b # c would be 4 + 6j
d = 3 * b # d would be 9 + 12j

That saves the definition of an extra class.
Also, expanding on previous answers,
class T(tuple):
    def __add__((x, y), (x1, y1)):
        return T((x+x1, y+y1))
    def __rmul__((x, y), other):
        return T((other * x, other * y))

would improve performance, at the cost of restraining the implementation to pairs.

A: There is the famous infix operator hack that would allow you to do soemthing like this:
x = Infix(lambda a,b:tuple([x+y for x, y in zip(a, b)]))
y = Infix(lambda a,b:tuple([a*y for y in b]))

c = a |x| b # c would be (4, 6)
d = 3 |y| b # d would be (9, 12)

That would hide the generator expressions and be applicable to tuples of all lengths, at the expense of "weird" pseudo-operators |x| and |y|.

A: Write your own class and implement __mul__, __add__ etc.

A: You can use numpy.array to get all you need.


text:
Q: How to Integrate instamojo marketplace api using PHP cURL I have to integrate your Marketplace API's using simple PHP cURL.
And I am using the test Sandbox link i.e. https://test.instamojo.com
My motive is:
1) I have the required account on instamojo
2) Use the Merchant Signup API to create accounts for my child merchants on my marketplace.
3) Get access tokens for my child merchants.
4) Add their bank information.
5) Create payment links for my child merchants and share them with buyers, or redirect the buyers to these payment links to receive payments.
I am stuck on the 2nd step.
I got my clientid and client_secret for C# but the 2nd step api showed following response:
{
"message": "You do not have permission to perform this action.",
"success": false
}
Hence I tried with credentials of JAVA Wrapper, WHMCS, OpenCart 2.3.x, Cs-Cart
But still no success. can any one help me out.

A: you have to generate access token using the Application Based Authentication and use that access_token to SignUp new users. Please refer the doc here https://docs.instamojo.com/v2/docs/signup


text:
Q: ReflectionTypeLoadException on DLL load I'm trying to realize a plugin framework with MEF. I have 3 projects:

*

*A host project (WPF)

*An interface definition project (portable class library)

*An plugin project (portable class library)

Now in the host, I try to load the plugin assemly dll (showing only the class that should load the dll):
public class SafeDirectoryCatalog : ComposablePartCatalog
{
    private readonly AggregateCatalog _catalog;

    public SafeDirectoryCatalog(string directory)
    {
        var files = Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories);

        _catalog = new AggregateCatalog();

        foreach (var file in files)
        {
            try
            {
                var asmCat = new AssemblyCatalog(file);

                if (asmCat.Parts.ToList().Count > 0)
                {
                    _catalog.Catalogs.Add(asmCat);
                }

            }
            catch (ReflectionTypeLoadException)
            {
            }
            catch (BadImageFormatException)
            {
            }
        }
    }
    public override IQueryable<ComposablePartDefinition> Parts
    {
        get { return _catalog.Parts; }
    }
}

on
var asmCat = new AssemblyCatalog(file);

I can see, that there is a "ReflectionTypeLoadException" and the parts list es emtpy:
Exception Screenshot (VS is German)
This is my interface definition (outputs a dll that is referenced in the host and the plugin project):
namespace HCInterfaces
{
    public interface HomeControlInterface
    {
        string GetModuleName();
    }
}

And finally this is my Plugin class that outputs the plugin.dll:
using HCInterfaces;
using System.Composition;

namespace Plugin2
{
    public partial class MainWindow
    {
        public MainWindow()
        {

        }

        [Export(typeof(HomeControlInterface))]
        class BMW : HomeControlInterface
        {
            public string GetModuleName()
            {
                return "hännschenklein";
            }
        }

    }
}

A: The issue will probably be library reference incompatibilities.
Maybe this link will help:
MEF 2 Composition with .NET 4.5, Windows Store PCL


text:
Q: Mips: function trouble Trying to create a function that so that f(0) = 8, and f(n) = 4f(n-1) - n + 5 if n > 0 recursively, but unable to get it to function correctly
 # $a0 = inpyt
 # $v0 = return value

f:     bnez  $a0, greaterthan0
       li $v0, 8
       jr $ra

greaterthan0: addi $sp,$sp,-8
              sw $ra, 0($sp)
              sw $a0,4($sp)
              sub $t3,$a0,1 # n-1=n
              jal f

              lw $ra, ($sp)
              lw $a0, 4($sp)
              addi $sp,$sp,8
              sll $t0,$t3,2 # mul n-1 by 4
              sub $t1,$t0,$t3
              addi $t2,$t1,5 # add 5 to n
              jr $ra

A: There are a few problems here.
The first problem here is that you are not following the convention that you have set out by passing the input in $a0 and returning the value in $v0.
To fix this, change sub $t3,$a0,1 # n-1=n to sub $a0,$a0,1 # n-1=n
and addi $t2,$t1,5 # add 5 to n to addi $v0,$t1,5 # add 5 to n.
Next there are some math errors in which variables you picked to evaluate f(n-1) - n + 5.
First, the comment mul n-1 by 4 is fundamentally wrong as we in fact want to multiple f(n-1) by 4. After the recursive call returns, the value of f(n-1) is of course stored in $v0.
Below is my fix:
 # $a0 = inpyt
 # $v0 = return value

f:     bnez  $a0, greaterthan0
       li $v0, 8
       jr $ra

greaterthan0: addi $sp,$sp,-8
              sw $ra, 0($sp)
              sw $a0,4($sp)
              sub $a0,$a0,1 # n=n-1
              jal f

              lw $ra, 0($sp)
              lw $a0, 4($sp)
              addi $sp,$sp,8

              sll $t0,$v0,2 # mul f(n-1) by 4
              sub $t1,$t0,$a0
              addi $v0,$t1,5 # add 5 to n
              jr $ra


text:
Q: Hibernate one to one mapping bi directional public class Driver {

    @OneToOne
    private License license;

    //.. getter setter
};

public class License {

    @OneToOne(mappedBy='license')
    private Driver driver;

   //.. getter setter
}

I get a join column license_id in the driver table in Db via this mapping. The problem is that:
Driver driver = new Driver();
// save driver then get it etc...

License license = new License();
license.setDriver(driver);
// save license...

driver.getLicense();

Although I set parent from child, the column is still empty and I get null.
How to avoid this?

A: Let's start with more descriptive mapping, and we can later remove parts, which will be relaized as defaults anyway.
There is a description which is more verbose than my extract. Please take a look at it:
http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/
Based on that let's extend the mapping this way:
The driver
public class Driver {

  @Id
  @GeneratedValue
  @Column(name="driver_id")
  private Long driverId;

  // cascade will do the job for us
  @OneToOne(mappedBy="driver", cascade=CascadeType.ALL)
  private License license;

The license
public class License {

  @Id
  @Column(name="driver_id", unique=true, nullable=false)
  @GeneratedValue(generator="gen")
  @GenericGenerator(name="gen", strategy="foreign"
           , parameters=@Parameter(name="property", value="driver"))
  private Long driverId;

  @OneToOne
  @PrimaryKeyJoinColumn
  private Driver driver
  ...

When inserting new value, we can set both ends explicitly:
Driver driver = new Driver();
License license = new License();
// set both ends
license.setDriver(driver);
driver.setLicense(license);

// Just save the Driver. the cascade will do the rest

And now Hibernate cascading functionality will the the rest for us

A: looks tacky but try to
public void setDriver(Driver driver){
    this.driver = driver;
    driver.setLicense(this);
}


text:
Q: Saving a table range in Excel as PDF I would like to export predefined excel table ranges (those from Excel 2007 & 2010) as PDF. Only the specific table should appear in the PDF, not the whole sheet.

A: Something like:
Sheet1.Range("B2:B7").ExportAsFixedFormat xlTypePDF, "C:\My Documents\Test.pdf"


text:
Q: In spree, Is there any possibilities to keep all checkout process steps in a single page? Is there any in-built feature is there in spree or we only need to customize that?

A: I recently published a blog post about this topic, hope it helps.
http://nebulab.it/blog/one-page-checkout-with-spree
The approach describes how to:

*

*change the checkout/edit.html.erb view to display all relevant checkout steps.

*add a :remote => true to all form_for but the last one.

*create a js view in checkout/edit.js.coffee which will replace the content of the next step in the right place.

A: You can try this demo to get more details, I think it will useful for you. link

A: you can try our the spree_one_page_checkout gem
But i really don't know if its worked correctly.

A: You would need to create your own version of that. I don't know of any extensions that offer that support.


text:
Q: Short story in which a microbiologist is prophesied to have a lab accident I'm looking for the name of a short story I read about 20 years ago, I read this as a translation in a magazine, I sadly have no idea how it was originally published. In which the protagonist, a microbiologist or some other sort of lab worker is "prophesied" to drop a sample of pathogens, causing a wide spread epidemic.
Facing an inability to go against this foreknowledge, the scientist throws the pathogenic sample in frustration, as per the prophesy. In the world of the story certain and accurate knowledge of the future is possible. If memory serves this is construded as a "science fictional " rather than a fantastic element, but no "technobabble" is supplied, if I remember correctly.

A: A bit of a long shot, but could this be one of the stories in either Machine of Death (2010) or its sequel This Is How You Die (2013), comprising the Death Machine series?
In these collections of short stories, the existence of a "death machine" is assumed, which will accurately although cryptically predict the manner of your death. For instance, "AIRPLANE" can mean dying in a plane crash, or being run over by one at an airport, or possibly choking on a toy plane.
I have only read a single story from one of the books. However, the scientific and accurate prediction did ring a bell. The timing would be a bit off, too, since the first book was published in 2010.


text:
Q: shnsplit failing to split multiple .flac files I am on Xubuntu 17.10 trying to split a .flac album file into tracks. When running the command
shnsplit -f "Master Of Puppets.cue" -o "flac flac -s -o %f -" "Side A.flac"

shnplit responds with:
shnsplit: warning: discarding initial zero-valued split point
shnsplit: error: split point 0 is not greater than previous split point 215871264

My cue sheet has more than one file in the album, and the second file starting with a split point of 0 is not being accepted.
My .cue file: https://pastebin.com/22T79tqP

A: Try to open cue file and split it into 2 cue files with the same header.
Then shnsplit side1.flac vs side1.cue and side2.flac vs side2.cue accordingly.


text:
Q: The cofiber sequence $\mathbb{C}\mathrm{P}^{n-1}\to\mathbb{C}\mathrm{P}^n\to S^{2n}$ $\newcommand{\CP}{\mathbb{C}\mathrm{P}}\newcommand{\Z}{\mathbb{Z}}$(Let the notation $H^*(X)$ represent $H^*(X;\Z)$, i.e. ordinary unreduced cohomology with $\Z$ coefficients.)
The standard inclusion $\CP^{n-1}\hookrightarrow\CP^{n}$ induces a cofiber sequence
$$\CP^{n-1}\longrightarrow\CP^{n}\longrightarrow S^{2n}$$
Since the connecting homomorphisms are trivial, there is a short exact sequence corresponding to this,
$$0\longrightarrow H^{2n}(S^{2n}) \longrightarrow H^{2n}(\CP^{n})\longrightarrow H^{2n}(\CP^{n-1})\longrightarrow 0$$
The cohomology ring $H^*(\CP^k)$ is isomorphic to $\Z[x]/(x^{k+1})$ with $|x|=2$, so this is just the short exact sequence
$$0\longrightarrow \Z\longrightarrow \Z\longrightarrow 0\longrightarrow 0$$
with the middle $\Z$ being the subgroup of $\Z[x]/(x^{n+1})$ generated by the multiples of $x^n$.
It seems only reasonable to assume that the image of $1\in\Z\cong H^{2n}(S^{2n})$ is the element $x^n\in H^{2n}(\CP^{n+1})$, but how do we know its image is not $-x^n$?
(In fact, I'm a little unclear on whether there is a canonical choice of an element $1$ in $H^{2n}(S^{2n})$, and similarly, if there is a canonical choice of element $x$ in $H^2(\CP^n)$. Does this have something to do with orientations?)
Thanks for any help!


text:
Q: How to display many pictures on form? how to display several pictures at once on some form, which are stored in a table ir_attachment ?
class Characteristic(models.Model):
    _inherit = "product.template"

    image_1 = fields.Many2many('ir.attachment', string="Image")