text:
Q: Upload a file within a form using another Controller [HttpPost] ActionLink How can I use my two controller Action in one form?
I can't figure a way to do two controller Action in the BeginForm().
I have this view on my project:
@using (Html.BeginForm()){
@Html.AntiForgeryToken()

T_Categorie

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.CatName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CatName, "", new { @class = "text-danger" })

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

            @Html.EditorFor(model => model.CatDesc, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CatDesc, "", new { @class = "text-danger" })

            Upload an image
            <input type="file" name="image" runat="server" style="width: 100%;" />

            <input type="submit" value="Create" class="btn btn-default" />

}

Here's my Category Create ActionLink which is in the T_CategorieController
        [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "CatName,CatDesc")] T_Categorie t_Categorie)
    {
        if (ModelState.IsValid)
        {

            db.T_Categorie.Add(t_Categorie);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(t_Categorie);
    }

Here's my file Uploader which is in the T_Images Controller
        [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase image, T_Categorie CurrentCat)
    {
        if (image != null)
        {
            if (image.ContentLength > 0)
            {
                byte[] imageData = null;
                using (var binaryReader = new BinaryReader(image.InputStream))
                {
                    imageData = binaryReader.ReadBytes(image.ContentLength);
                }

                try
                {
                    //Upload to database
                    T_Images newImage = new T_Images { ImgData = imageData };
                    db.T_Images.Add(newImage);
                    db.SaveChanges();
                    //Change the currentCat fk_ImgId
                    var CurrentImageDB = db.T_Images.OrderByDescending(t => t.ImgId).First();
                    var currentRefCat = db.T_Categorie.Find(CurrentCat.CatId);
                    //
                    currentRefCat.fk_ImgID = CurrentImageDB.ImgId;
                    db.SaveChanges();
                }
                catch (System.Data.SqlClient.SqlException)
                {
                    throw new FileLoadException();
                }
            }
        }
        return RedirectToAction("Index", "Home");
    }

A: I needed to pass a parameter to the Html.BeginForm()
Since the [HttpPost] Bind a model to my create ActionLink I just have to reference my image in the BeginForm()
my view BeginForm procedure:
@using (Html.BeginForm("Create", "T_Categorie", FormMethod.Post, new { enctype = "multipart/form-data" }))

My Controller is redirecting my CreateActionLink to the FileUpload Procedure
            [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(HttpPostedFileBase IMG, [Bind(Include = "CatName,CatDesc")] T_Categorie t_Categorie)
    {
        if (ModelState.IsValid)
        {
            db.T_Categorie.Add(t_Categorie);
            db.SaveChanges();
            var addedCategory = db.T_Categorie.Find(t_Categorie.CatName);
            return RedirectToAction("FileUpload", "T_Images", new { image = IMG, CurrentCat = addedCategory });
        }

        return View(t_Categorie);
    }


text:
Q: Invocation of toString on an array - FindBugs I am getting the below Findbugs error for my code,
Invocation of toString on <<Package Path>>

 The code invokes toString on an array, which will generate a fairly useless
 result such as [C@16f0472. Consider using Arrays.toString to convert the
 array into a readable String that gives the contents of the array.
 See Programming Puzzlers, chapter 3, puzzle 12.

Code:
logger.info("Adding information"+ Employee.getName()+ " "+
            employeeForm.getQuestionAndAnswers());

Please let me know what is the error.

A: As it says, doing
myArray.toString()

will generate something useless like java.lang.int[]@45345262
you'd want to use
Arrays.toString(myArray);

redpajama_set_name: RedPajamaStackExchange


text:
Q: No se están insertando en la base los datos de un formulario Estoy realizando un sistema de inventarios lo cual utilizo PHP y SQL Server 2008. Al realizar una conexión a la base de datos todo es exitoso, pero al ingresar datos en los formularios desde PHP no inserta ningún dato a la base.
<?php

    $serverName = ("Localhost"); //serverName\instanceName, portNumber (por defecto es 1433
    $connectionInfo = array("Database"=>"new", "UID"=>"", "PWD"=>"");
    $conexion = sqlsrv_connect($serverName, $connectionInfo);
    //include('conexion.php');

    if($conexion===false)
    {
        die(print_r (sqlsrv_errors(),true));

    }

    if ($_POST)

   {
      $id_usuario_final =$_POST['id_usuario_final'];
      $nombre =$_POST['nombre'];
      $ap =$_POST['ap'];
      $am=$_POST['am'];
      $fecha=$_POST['fecha'];
      $localidad=$_POST['localidad'];
      $departamento=$_POST['departamento'];

      $tsql= "INSERT into 'new.Usuarios' (id_usuario_final,nombre,ap,am,fecha,localidad,departamento)
      values ('$id_usuario_final','$nombre,'$ap','$am','$fecha','$localidad','$departamento')";

     $param1=array($id_usuario_final,$nombre,$ap,$am,$fecha,$localidad,$departamento);

     $recurso=sqlsrv_query($tsql,$param1);

     sqlsrv_close($connectionInfo);

   }
?>

<form name="pru"  method="post">

<fieldset style="width:30%" "width:600px">

    <legend>Información de Usuarios</legend>

       ID Usuario:
        <input type="text" name="id_usuario_final"

       Nombre:
        <input type="text" name="nombre"

       Apellido Paterno:
        <input type="text" name="ap"

       Apellido Materno:
        <input type="text" name="am"

         Fecha:
          <input type="date" name="fecha"

         Localidad:
          <input type="text" name="localidad"

         Departamento:
          <input type="text" name="departamento"

	</fieldset>

</form>

A: Prueba modificando la linea:
$tsql= "INSERT into 'new.Usuarios' (id_usuario_final,nombre,ap,am,fecha,localidad,departamento)
  values ('$id_usuario_final','$nombre,'$ap','$am','$fecha','$localidad','$departamento')";

por esta:
$tsql= "INSERT into Usuarios (id_usuario_final,nombre,ap,am,fecha,localidad,departamento)
  values ('$id_usuario_final','$nombre,'$ap','$am','$fecha','$localidad','$departamento')";

Edit: Otra cosa. La columna id_usuario_final es un dato tipo Int? En ese caso, deberías sacar las comillas en el String $tsql.
Exitos!


text:
Q: Passing an Auto_Open macro from one workbook to another I have to pass an Auto_Open macro from one Excel file to about one hundred other Excel files, which are generated automatically from R-script. I really don't know the VBA code.
At first I hoped that opening the file containing the macro and then opening the rest of the files will do the work, but unfortunately it didn't happen and I assume I have to pass the VBA code to all the files.
This macro does a little bit of formatting and limits the values in some cells. I found similar subject but I had problems with modifying VBA code to solve my problem. Is there any way to do simply copy that?

A: One solution would be to create a template containing the "Auto_Open" Macro and use this template to generate the hundreds of files with the "R-Script"


text:
Q: How can I add animation to react state I just want to add a fade in animation to next index. i found a package called "react transition group" but all tutorials were based on class components or redux I didn't understand anything.

const AboutTestimonials = () => {
  const [index, setIndex] = useState<any>(0);
  const [data] = useState(AddTestimonial);
  const current = data[index];

  return (

TESTIMONIALS

{current.quote}

{current.postedby}

{current.profession}

        <Image
          src={leftarrow}
          alt="arrow"
          onClick={() => setIndex(index > 0 ? index - 1 : index)}
          className="pagination__arrows"
        />

{index + 1} / 5

        <Image
          src={rightarrow}
          alt="arrow"
          onClick={() => setIndex(index < 4 ? index + 1 : index)}
          className="pagination__arrows"
        />

A: SwitchTransition waits for the old child to exit then render the new child as mentioned in the react transition group website.
there are two modes:

*

*in-out

*out-in

the important factor is changing the key prop of the child component.child component could be CSSTransition or Transition.if you want the transition changes simultaneously you can use the TransitionGroup.

side note: if you want to use the AddTestimonial in your component and you don't want to change the state (I noticed there is no second argument for setting the data), there is no need to declare a useState.it is much better to set AddTestimonial  as a prop on AboutTestimonials component

import { CSSTransition, SwitchTransition } from 'react-transition-group';
const AboutTestimonials = () => {
  const [index, setIndex] = useState<any>(0);
  const [data] = useState(AddTestimonial);
  const current = data[index];

  return (

TESTIMONIALS

        <SwitchTransition mode={'out-in'} >
         <CSSTransition
           key={index}
           timeout={300}
           classNames="fade"
           >
          <>

{current.quote}

{current.postedby}

{current.profession}

          </>
         </CSSTransition>
       </SwitchTransition>

        <Image
          src={leftarrow}
          alt="arrow"
          onClick={() => setIndex(index > 0 ? index - 1 : index)}
          className="pagination__arrows"
        />

{index + 1} / 5

        <Image
          src={rightarrow}
          alt="arrow"
          onClick={() => setIndex(index < 4 ? index + 1 : index)}
          className="pagination__arrows"
        />

)}

css:
.fade-enter {
  opacity: 0;
}
.fade-enter-active {
  opacity: 1;
  transition: opacity 300ms;
}
.fade-exit {
  opacity: 1;
}
.fade-exit-active {
  opacity: 0;
  transition: opacity 300ms;
}


text:
Q: In gitweb, how can I set the parent when doing a diff on a merged commit? Please note, this question is about GITWEB, not git. I know how to do this in git, but I would like to be able to perform it in gitweb so I can easily show my changes to people I work with.
If I have a tree that looks like this:
*--C--D     master
 \     \
  *-A---B   proj-1
        ^
        merge commit, has 2 parents

I would like to be able to see the differences between B and D. This should show the changes of A & B vs C & D. However, when I use git web (specifying the commit hash), it just shows me what's in D. Is there any way to set the parent when using commitdiff on a merge commit?

A: I know this is an old question but I may have the answer... Try just adding/changing the hp parameter to the new parent SHA in the URL:
https://gitweb.server.com/?p=REPONAME;a=commitdiff;h=SHA;hp=PARENTSHA

This works on my gitweb server.


text:
Q: In Python, how to do a grouped rolling average/standard deviation excluding current date and when dates are non-consecutive? I am rather new to Python (migrating from R) and working on some rolling average/rolling standard deviation data.
So I have a date column, a category column and a rate of change column.  For each date, I would like to get a rolling 10 days average of the rate of change data.  However I would like to exclude the current date in calculation.  And for my dates, they are not consecutive.
My dataframe looks like below,   dataframe
and I am would like to create columns like below
result
I really tried my best to glance through most questions here but cannot find exactly same question.  Some solution is to loop every row by using iterrow(), but my full dataset is around 70k entries and it is too slow to do so (maybe I write the code badly).
I also tried groupby rolling with shift.  But since the dates are non-consecutive, I find work it out too.
Here are some background for the study.  We need the rolling sum/mean/sd for decision making of next period.  However the last period data only comes after the next period started, that we have to exclude the current date data to remove look-ahead bias.  And the rate of change report does not comes daily, and each period not every items are reported.
My code in R is like this
df[,RollingMean := df[.(Item, Date , Date %m-% days(10)),on = .(Item = V1, Date < V2, Date >= V3), mean(Rate_of_Chg), by = .EACHI]$V1]
df$RollingMean <- df$RollingMean %>% replace_na(0)
Could I pick you guys brain on this?  Thanks!!

A: A typical approach is to first impose a daily frequency (some days will have missing values) then use the rolling methods. To exclude the last date you can easily sort by the index (date) and use the .iloc method of pandas. For example:
# assume df is a pandas (pd) dataframe
# and Date is one of the columns

# 1. Set the index
df.set_index("Date", inplace=True)

# 2. Make sure the index is datetime
df.index = df.index.map(pd.to_datetime)

# 3. Resample to daily and sort it
df2 = df.resample('D').last().sort_index()

# 4. rolling method ex the last date
avg = df2.iloc[:-1].rolling(10).mean()

EDIT: added sort index and iloc to exclude the last date.


text:
Q: Named object inside an array inside of an object I have a node.js model, in which I have an array named keys. Inside this array I have a bunch of objects. I need to get these objects named in the view.
Here's the model:
var mongoose = require('mongoose');

var website = require('./website');

var plm = require('passport-local-mongoose');

var accountSchema = new mongoose.Schema({
  isPremium: Boolean,
  accType: String,
  websites: [],
  keys: []
});

accountSchema.plugin(plm);

module.exports = mongoose.model('Account', accountSchema);

And here's the view:
<% include ./../partials/header.ejs %>

    <%= title %>

      User
      <% if (user) { %>
        Actions
        <% } %>

    <% for(let i=0; i<users.length; i++){ let user = users[i] %>

          <%= user.username %>

          <%= user.keys[i].name %>

          <a href="/admin/edit/<%= i %>" class="btn btn-info">Edit
          <%#Delete%>

      <% } %>

  <% include ./../partials/footer.ejs %>

I am trying to populate the keys during the registration like this:
/* POST register */
router.post('/register', function(req, res, next) {
  // use the Account model to create a new user with passport
  Account.register(
    new Account({
      username: req.body.username,
      isPremium: false,
      websites: [
        req.body.websiteOwned,
        req.body.websiteCompet1,
        req.body.websiteCompet2,
      ],
      keys: [
        { name: 'Google', key: '' },
        { name: 'Built With', key: '' },
        { name: 'Check Host', key: '' },
        { name: 'Alexa', key: '' },
        { name: 'Facebook', key: '' },
        { name: 'Instagram', key: '' },
        { name: 'Moz', key: '' },
      ], // accType: 'admin',
    }),
    req.body.password,
    function(err, account) {
      if (err) {
        // failure
        console.log(err);
        res.redirect('error', { title: 'Create Account Error' });
      }
      res.redirect('/login'); // success
    }
  );
});

There are a couple of things I don't understand. When I register like this, all it prints in the view is: Object object.
When my model is like this:
var accountSchema = new mongoose.Schema({
  isPremium: Boolean,
  accType: String,
  websites: [],
  keys: [
    { name: String, key: String },
    { name: String, key: String },
    { name: String, key: String },
    { name: String, key: String },
    { name: String, key: String },
    { name: String, key: String },
    { name: String, key: String },
  ],
});

It prints out { name: 'Google', key: '' } which is ok because I have one user and i is 0. But when I edit my view to this:
<% for(let i=0; i<users.length; i++){ let user = users[i]; %>

      <%= user.username %>

    <% for(let j=0; j<keys.length; j++) { %>
      <%= user.keys[j] %>
    <% } %>

      <a href="/admin/edit/<%= i %>" class="btn btn-info">Edit
      <%#Delete%>

  <% } %>

So I added a loop inside, it says keys is not defined. So I'm guessing I'm messing something with scope?
My second issue is: When I'm trying to access a property of an object in the keys array like this: user.keys[i].name I get this error: Cannot read property 'name' of undefined.
What am I doing wrong and how do I fix it? Is it possible to use the first model( keys=[] ) in implementation? It would be more future-proof.

A: I have no idea why, but when after I deleted and added it a couple of times, mongoose suddenly added the objectId field to all 7 objects in the array. It works fine with objectId. I would appreciate an explanation if anyone understands what happened here.


text:
Q: Firebase cloud functions deployment issue when using Github package as npm node module I'm using github repo tag as npm module in my Firebae cloud functions project and it's working fine in local env.
//package.json
"@instantish/martian": "github:Rakmo33/martian#v2.3.0",

However, when I deploy to Firebase cloud functions it throws following error:
"Build failed: npm ERR! Error while executing:\nnpm ERR! /usr/bin/git ls-remote -h -t ssh://git@github.com/Rakmo33/martian.git\nnpm ERR! \nnpm ERR!
Host key verification failed.\nnpm ERR! fatal: Could not read from remote repository.\nnpm ERR! \nnpm ERR!
Please make sure you have the correct access rights\nnpm ERR! and the repository exists.\nnpm ERR! \nnpm ERR! exited with error code: 128\n\nnpm ERR!
A complete log of this run can be found in:\nnpm ERR! /www-data-home/.npm/_logs/2021-11-25T10_28_13_554Z-debug.log; Error ID: beaf8772"

A: Don't know the details of your project, but the fact is if you had executed:
npm install git+https://git@github.com/Rakmo33/martian.git#v2.3.0

you would have something like this within your package.json:
"dependencies": {
    "@rakmo33/martian_fork": "git+https://git@github.com/Rakmo33/martian.git#v2.3.0"
  }

and you'd have avoided the necessity of using any password-protected SSH keys.


text:
Q: Add In Plot Labels to Seaborn Lineplot I have a dataframe that shows monthly revenue. There is an additional column that shows the number of locations opened in that month.
>       Date        Order Amount    Locations Opened
  16    2016-05-31  126443.17       2.0
> 17    2016-06-30  178144.27       0.0
  18    2016-07-31  230331.96       1.0
> 19    2016-08-31  231960.04       0.0
  20    2016-09-30  208445.26       0.0

I'm using seaborn to plot the revenue by month
    sns.lineplot(x="Date", y="Order Amount",
                data=total_monthly_rev).set_title("Total Monthly Revenue")

I've been trying, unsuccessfully, to use the third column, Locations Opened, to add supporting text to the lineplot so I can show the number of locations opened in a month, where Locations Opened > 0.

A: IIUC, use text:
plt.figure(figsize=(12, 5))
sns.lineplot(x="Date", y="Order Amount", data=total_monthly_rev).set_title("Total Monthly Revenue")

# Using a variable to manage how above/below text should appear
slider = 1000
for i in range(total_monthly_rev.shape[0]):
    if total_monthly_rev['LocationsOpened'].iloc[i] > 0:
        plt.text(total_monthly_rev.Date.iloc[i],
                 total_monthly_rev['Order Amount'].iloc[i] + slider,
                 total_monthly_rev['LocationsOpened'].iloc[i])
plt.show()


text:
Q: image compression c# and recoverred in android I am storing an image in sql server from a c# application and displaying it in android.
I am getting a memory problem in android and the queries to sql are taking to much time so, I would like to know a way to compress the image in c# to, for example, 100 KB, and store it in sql with this size.
--EDIT
This is the code when displaying the image in android:
Bitmap bitmap=BitmapFactory.decodeByteArray(myLote.getFoto(), 0, myLote.getFoto().length);
    imageFoto.setImageBitmap(bitmap);

imageFoto is the ImageView and "myLote.getFoto()" returns the byte[]
08-06 18:03:41.300: E/AndroidRuntime(6462): FATAL EXCEPTION: main
08-06 18:03:41.300: E/AndroidRuntime(6462): java.lang.OutOfMemoryError
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:428)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:446)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at com.example.subasta.FragmentSubasta.onViewCreated(FragmentSubasta.java:109)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.os.Handler.handleCallback(Handler.java:725)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.os.Looper.loop(Looper.java:137)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at java.lang.reflect.Method.invokeNative(Native Method)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at java.lang.reflect.Method.invoke(Method.java:511)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-06 18:03:41.300: E/AndroidRuntime(6462):     at dalvik.system.NativeStart.main(Native Method)

--REEDIT
I am not getting now any error but nothing is displayed :( :
BitmapFactory.Options options=new BitmapFactory.Options();
    options.inSampleSize = 2;
    Bitmap preview_bitmap = BitmapFactory.decodeByteArray(myLote.getFoto(), 0, myLote.getFoto().length, options);
    imageFoto.setImageBitmap(preview_bitmap);

Thank you all.

A: Use the lower common that possible save the image in SQL as byte array  byte[]
then you can convert from byte[] to Bitmap in Android.


text:
Q: How to check if NSString begins with a certain character How do you check if an NSString begins with a certain character (the character *).
The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.

A: hasPrefix works especially well.
for example if you were looking for a http url in a NSString, you would use componentsSeparatedByString to create an NSArray and the iterate the array using hasPrefix to find the elements that begin with http.
NSArray *allStringsArray =
   [myStringThatHasHttpUrls componentsSeparatedByString:@" "]

for (id myArrayElement in allStringsArray) {
    NSString *theString = [myArrayElement description];
    if ([theString hasPrefix:@"http"]) {
        NSLog(@"The URL  is %@", [myArrayElement description]);
    }

}

hasPrefix returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
- (BOOL)hasPrefix:(NSString *)aString,

parameter aString is a string that you are looking for
Return Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.

A: As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.
NSString* myString = @"10:Username taken";

if([myString hasPrefix:@"10"]) {
      //display more elegant error message
}

A: You can use the -hasPrefix: method of NSString:
Objective-C:
NSString* output = nil;
if([string hasPrefix:@"*"]) {
    output = [string substringFromIndex:1];
}

Swift:
var output:String?
if string.hasPrefix("*") {
    output = string.substringFromIndex(string.startIndex.advancedBy(1))
}

A: Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.

A: NSString *stringWithoutAsterisk(NSString *string) {
    NSRange asterisk = [string rangeOfString:@"*"];
    return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}

A: Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
  //starts with http
}

A: You can use:
NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:@"*"] ) {
     newString = [myString substringFromIndex:1];
}

A: This might help? :)
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/characterAtIndex:
Just search for the character at index 0 and compare it against the value you're looking for!

A: This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:
NSString = [yourString stringByReplacingOccurrencesOfString:@"YOUR CHARACTERS YOU WANT TO REMOVE" withString:@"CAN either be EMPTY or WITH TEXT REPLACEMENT"];

This is how I use it:
//declare what to look for
NSString * suffixTorRemove = @"
";
NSString * prefixToRemove = @"
";
NSString * randomCharacter = @"";
NSString * moreRandom = @"";
NSString * makeAndSign = @"&";

//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:@"&"];

//check the output
NSLog(@"returnStr IS NOW: %@", returnStr);

This one line is super easy to perform three actions in one:

*

*Checks your string for the character/s you do not want

*Can replaces them with whatever you like

*Does not affect surrounding code

A: NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
   expectedString = [givenString substringFromIndex:1];
}


text:
Q: Is it possible to track subfolders using Google Analytics from one file? Let's say this is my directory structure:
ROOT
index.php -- Folder 1 -> file.php
          -- Folder 2 -> file.php
            |-- subfolder -> file.php
          -= Folder 3 -> file.php

and I need to put my tracking code on my index.php file, but I need this single code to track the activity on every single folder that is a child of the folder where index.php is.
I just need to insert the tracking code on index.php, or should I do something else, like using a php require commend?
EDIT:
Finally made it, here is how I've put things to work:
Insert Google Analytics in php (Am I doing it the right way?)

A: Ultimately, you will want the Analytics tracking code to appear on every page of your site you wish to track.
Once solution could be to include your tracking code in a PHP file (say, analytics.php), and require it after opening the <body> tag of your pages.


text:
Q: How do I not allow submission for empty fields from a child component? More explanation below I have this sample codesandbox I made, though, in my original one there were already a lot of values. I only recreated the problem that I had.
Codesandbox: https://codesandbox.io/s/youthful-firefly-40mig3?file=/src/App.js
I have this in my App.js where I define some of my needed values and then pass it to 2 other components.

      {/* some codes here */}

App page

      Initial Amount: 1000

      Total Amount: {totalAmount}

      ----------------------------------------------------------

Passing the total amount and the second input here

      <Second input2={input2} setInput2={setInput2} />
      ----------------------------------------------------------

Third here

      <Third totalAmount={totalAmount} />

I have this Second.js where I compute the totalAmount. This is the problem that I encountered. The required is not being recognized here. I just wanted to stop the user from submitting the form if this field is empty. Are there other ways where it would not submit if a certain field is empty or just leave the input field to 1 if it is empty?
const Second = ({ input2, setInput2 }) => {
  return (

      Second here
      <form>
        <input
          fullWidth
          value={input2}
          onChange={(e) => setInput2(e.target.value)}
          required
        />
      </form>

  );
};
export default Second;

This is the Third.js where I passed down the totalAmount and added more values such as the name and age. In here the name and age are being recognized. This is also where I submit everything here.
const Third = ({ totalAmount }) => {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      console.log(name, age, totalAmount);
    } catch (err) {
      console.log(err);
    }
  };
  return (

      Third here
      <form onSubmit={handleSubmit}>
        Name
        <input
          fullWidth
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
        />

        Age
        <input
          fullWidth
          value={age}
          onChange={(e) => setAge(e.target.value)}
          required
        />

        <button type="submit">submit</button>
      </form>

  );
};
export default Third;

A: You can pass the input2 as a prop to Third.js and there you can check if input2 doesn't exist then don't submit the values.
In the App.js pass input2 to the Third component.
<Third totalAmount={totalAmount} input2={input2} />

Then in Third.js check if the input2 value exists.
const Third = ({ totalAmount, input2 }) => {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (input2) {
      try {
        console.log(name, age, totalAmount);
      } catch (err) {
        console.log(err);
      }
    }else {
      alert('Please enter the second value');
    }
  }
}


text:
Q: Parameterize link elements in QTP How to parametrize link elements in QTP?
I have an order number in my application. I click on that number to find its detail. QTP save this as a link. Now I want to see detail of another order. I have parametrize the order number. Now QTP pick new number from datasheet. But as the link saved is for the previous order so that order is getting opened not the new one.

A: If you use descriptive programming, parameterize object description through variable.
Example:
 [...].Link("name:=order" & intOrderNumber)

If you use mapping through repository, parameterize property value directly to datatable. You can find a very good explanation with screenshots in QTP help.

A: Use descriptive for this. First check the property of that link changing every time with order number (name, display name etc.). Then use that property name like below:
B(...).p(...).link("propertyname:="&ordernumber,"index:=0")

The index is for unique identification.

A: You can parameterize with descriptive programming or you can also parameterize from Object repository which I would not suggest. You can go to object repository Click on that button in object repository there you can find  + sign near by test object details click on that and add description properties "Outerhtml" and parameterize or use regular expression . You can also parameterize from Object repository. However, adding objects to object repository would only make things slow.  Descriptive programming is better.


text:
Q: One extra line being read in file handling I am trying to get the number of lines and words from a text file in c++. But one extra line is being read by compiler.
#include <iostream>
#include<fstream>
using namespace std;

int main(void)
{
    ifstream f;
    string name;
    char a;
    int line, words;
    line = 0;
    words = 0;

    f.open("file.txt");

    while (f) {
        f.get(a);

        if (a == '\n')
        {
            line++;
            words++;
        }

        if (a == ' ')
        {
            words++;
        }

    }
    f.close();
    cout << "Number of words in file : " << words << endl;
    cout << "Numbers of lines in the file : " << line << endl;
}

OUTPUT:-
Number of words in file : 79
Numbers of lines in the file : 3

file.txt:-
This C++ Program which counts the number of lines in a file. The program creates an input file stream, reads a line on every iteration of a while loop, increments the count variable and the count variable is printed on the screen.
Here is source code of the C++ program which counts the number of lines in a file. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

I am puzzled why one extra line is being read. Kindly help.

A: You are not checking if f.get() succeeds or fails.  When it does fail, a is not updated, and you are not breaking the loop yet, so you end up acting on a's previous value again. And then the next loop iteration detects the failure and breaks the loop.
Change this:
while (f) {
    f.get(a);
    ...
}

to this instead:
while (f.get(a)) {
    ...
}

That being said, you are also not taking into account that the last line in a file may not end with '\n', and if it does not then you are not counting that line.  And also, you are assuming that every line always has at least 1 word in it, as you are incrementing words on every '\n' even for lines that have no words in them.
I would suggest using std::getline() to read and count lines, and std::istringstream to read and count the words in each line, eg:
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;

int main(void)
{
    ifstream f;
    string line, word;
    int lines = 0, words = 0;

    f.open("file.txt");

    while (getline(f, line))
    {
        ++lines;
        std::istringstream iss(line);
        while (iss >> word) {
            ++words;
        }
    }

    f.close();

    cout << "Number of words in file : " << words << endl;
    cout << "Numbers of lines in the file : " << line << endl;
}

A: It is because you do not check in what state is stream that f.get(a) returns.


text:
Q: Need easier way to replace nested custom tags with HTML equivalents I'm looking for a way to properly replace nested custom tags with their HTML equivalents.  For example, suppose we have the following text:
This is {b:bold text}

Which should become:
This is bold text

I'm aware that I can - and probably should - use something like a span with a "bold" class instead of the old "b" tags, but there's a reason I'm sticking with "b" for the purpose of this example.  I may have nested tags:
This is {b:bold text and {i:italic}}

which should become:
This is bold text and italic

However, I have these regexes (which I use with the replace() function):
/\{b:([\s\S]*?)\}/gm
/\{i:([\s\S]*?)\}/gm

And then the result will become:
This is bold text and italic

The tags are not properly nested.  Again, using spans can solve this in this case, but that won't work with things like "ul", "li", "h1", ...
Greedy regexes will also cause problems if the text looks like this:
This is {b:bold text} and {i:italic}

So my current solution is to replace everything with span first, using a data-tag attribute to indicate what it should actually be, and then use jQuery to find all span nodes and replace them with the proper tags:
{h:This is a header}
becomes
This is a header
becomes

This is a header

It works well, but i'm wondering if there is an easier way to do this.  The intermediate  method feels a bit like a duct tape solution and I would like to "beautify" it.
Any suggestions?

A: A simple stack goes a long way
function doReplace( str ) {
    var stack = [],
        ret = [],
        ch;
    for( var i = 0, l = str.length; i < l; ++i ) {
        var ch = str.charAt(i);

        if( ch === "{" ) {
            var pos = str.indexOf( ":", i+1);
            if( pos < 0 ) {
                throw new SyntaxError();
            }
            var tagName = str.substring( i + 1, pos);
            if( /[^A-Za-z0-9]/.test(tagName)) {
                throw new SyntaxError();
            }
            ret.push( "<" + tagName + ">" );
            stack.push( tagName);
            i+= tagName.length + 1;
        }
        else if( ch === "}" ) {
            if( !stack.length ) {
                throw new SyntaxError();
            }
            var tagName = stack.pop();
            ret.push( "</" + tagName + ">" );
        }
        else {
            ret.push( ch );
        }
    }

    if( stack.length ) {
        throw new SyntaxError();
    }

    return ret.join("");
}

doReplace( "This is {b:bold text {i:italic text{i:italic text{i:italic text{i:italic text{i:italic text{i:italic text}}}}}}}")
//"This is bold text italic textitalic textitalic textitalic textitalic textitalic text"

A: Ditch the Regex and use one of the many templating tools out there, such as Mustache, or t.js.
EDIT: Fixed!
...but if you are avoiding such simplicities in life, here's how to do it with a regular expression:
var rex = /\{(b|i):([^{}]*)\}/igm,
    parse = function(txt) {
        var cnt = 0,
            more = true;
        while (more) {
            txt = txt.replace(rex, function(match, $1, $2) {
                return "<" + $1 + ">" + $2 + "</" + $1 + ">";
            });
            more = rex.test(txt);
            cnt++;
        }
        return txt;
    };

So you call parse and pass it your string. It recursively parses your string until no other mark-up is found. This new one works in reverse, parsing out the items that don't have items within, then moving outward.
To implement the H1 example that you added, you could either instead us {h1:This is the header} and add it to the (b|i) clause, or use a switch statement in the replace function instead of just returning $1.
Here's the JSFiddle.


text:
Q: Replacing last two characters in PySpark column In a spark dataframe with a column containing date-based integers (like 20190200, 20180900), I would like to replace all those ending on 00 to end on 01, so that I can convert them afterwards to readable timestamps.
I have the following code:
from pyspark.sql.types import StringType
import pyspark.sql.functions as sf

udf = sf.udf(lambda x: x.replace("00","01"), StringType())

sdf.withColumn('date_k', udf(sf.col("date_k"))).show()

I also tried:
sdf.withColumn('date_k',sf.regexp_replace(sf.col('date_k').cast('string').substr(1, 9),'00','01'))

The problem is this doesn't work when having for instance a value of 20200100, as it will produce 20201101.
I tried also with '\\00', '01' , it does not work. What is the right way to use this regex for this purpose?

A: Try this. you can use $ to identify string ending 00 and use regexp_replace to replace it with 01
    # Input DF
    df.show(truncate=False)

    # +--------+
    # |value   |
    # +--------+
    # |20190200|
    # |20180900|
    # |20200100|
    # |20200176|
    # +--------+

    df.withColumn("value", F.col('value').cast( StringType()))\
        .withColumn("value", F.when(F.col('value').rlike("(00$)"), F.regexp_replace(F.col('value'),r'(00$)','01')).otherwise(F.col('value'))).show()

    # +--------+
    # |   value|
    # +--------+
    # |20190201|
    # |20180901|
    # |20200101|
    # |20200176|
    # +--------

A: This is how I solved it.
Explanation first cut the number for first part excluding last two digits and in second do regex replace, then concat both parts.
import pyspark.sql.functions as f
df = spark.sql("""
select 20200100 as date
union
select 20311100 as date
""")

df.show()
"""
+--------+
|    date|
+--------+
|20311100|
|20200100|
+--------+
"""

df.withColumn("date_k", f.expr("""concat(substring(cast(date as string), 0,length(date)-2),
                               regexp_replace(substring(cast(date as string), length(date)-1,length(date)),'00','01'))""")).show()

"""
+--------+--------+
|    date|  date_k|
+--------+--------+
|20311100|20311101|
|20200100|20200101|
+--------+--------+

"""


text:
Q: what happens on connection.setAutoCommit = false what happens if I do connection.setAutoCommit(false); does it creates a new transaction at database side?

A: According to the documentation, connection.setAutoCommit(false) will allow you to group multiple subsequent Statements under the same transaction. This transaction will be committed when connection.commit() is invoked, as opposed to after each execute() call on individual Statements (which happens if autocommit is enabled).
Changing the auto-commit mode through connection.setAutoCommit() will implicitly commit the active transaction and create a new one. From the Javadocs:

NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed. If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op.

A: The implementation of each method inside JDBC API depends on each driver. Oracle may do something very different than MySql does.
However, only calling connection.setAutoCommit(false); doesn't creates a transaction. It only means that any statement created using this connection will be committed together when you call connection.commit();.
Take a look at this Oracle tutorial.

A: Let me put it with simple explanation with code. When we have applied

Connection.setAutoCommit(false);

in our source code, it will disable the autocommit option, which by default enable in database.
So, you have to call

Connection.commit();

method explicitly to persist any changes to the database.
Class.forName(drivers);
Connection dbConnnection=DriverManager.getConnection(connectionURL,username,password);
dbConnection.setAutoCommit(false); //Disabling the Autocommit
Statement selectStatement = dbConnection.createStatement("Select Query");
ResultSet rs = selectStatement.execute();
while(rs.next()){
    Statement updateStatement = dbConnection.createStatement("update Query");
    //Apply some changes to update record
    statement.execute();
    dbConnection.commit();  //Mandatory to execute to persist changes into database
}

A: The JavaDocs provide a nice explanation of this use case in the Using Transactions Section

Disabling Auto-Commit Mode
When a connection is created, it is in auto-commit mode. This means
  that each individual SQL statement is treated as a transaction and is
  automatically committed right after it is executed. (To be more
  precise, the default is for a SQL statement to be committed when it is
  completed, not when it is executed. A statement is completed when all
  of its result sets and update counts have been retrieved. In almost
  all cases, however, a statement is completed, and therefore committed,
  right after it is executed.)
The way to allow two or more statements to be grouped into a
  transaction is to disable the auto-commit mode. This is demonstrated
  in the following code, where con is an active connection:
con.setAutoCommit(false);


text:
Q: Set a category for a page My current theme has a portfolio section where you can have an array items based on what category they are in. My problem is that I have several pages that I want to be in the portfolio section but can't add them there because you can't assign categories to individual pages only posts. Is there any method or plugin around this issue?
This is some code that I believe calls the category in my portfolio.php:
<?php  if(is_category() && in_category($current_id) || post_is_in_descendant_category($current_id)){?>

<?php single_cat_title(); ?>

<a href="<?php echo get_category_link(get_option('boldy_portfolio'))?>">All projects

            <?php
                    $categories = get_categories('hide_empty=1&child_of='.$categs);
                    foreach ($categories as $cat) {
                    echo ('
cat_ID).'">'.$cat->cat_name.'
');
                    }
                ?>

    <?php } ?>

            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<a href="<?php the_permalink() ?>"><?php the_title(); ?>

                        <a href="<?php echo get_thumb_urlfull($post) ?>" rel="prettyPhoto" title="<?php the_title();?>"><?php the_post_thumbnail(); ?>

<?php the_excerpt() ?>

            <?php endwhile; ?>

Thanks Nick.

A: Category is a taxonomy that applies to Posts. Pages are not Posts. Pages are Pages.
If you need your content to use the Category taxonomy, you have a couple options:

*

*Use Posts, rather than Pages, for that content.

*Register the Category taxonomy for static Pages, e.g. by placing the following in functions.php (or in a Plugin):
Which will enable Categories for static Pages.
Grr... code doesn't want to show:
<?php
register_taxonomy_for_object_type( 'category', 'page' );
?>

Edit 2
The correct way to modify the main loop query is via pre_get_posts, e.g. like so:
function wpse29834_filter_pre_get_posts( $query ) {
    if ( is_category() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'wpse29834_filter_pre_get_posts' );

Using pre_get_posts is preferred over using query_posts(), though the original solution works in this case.
(Original Solution)
To get your categorized Pages to display in the Loop on your category archive indexes, you'll need to modify the Loop query in category.php, which you do using the query_posts() function. e.g.:
<?php
// Declare the global
global $wp_query;
// Define our custom args
// We're telling the query to use
// both Posts and Pages
$custom_args = array( 'post_type' => array( 'post', 'page' ) );
// Merge the default query with our custom query
$query_args = array_merge( $wp_query->query, $custom_args );
// Finally, query posts based on our custom args
query_posts( $query_args );
?>

Place this code before you output the Loop.


text:
Q: How to count how many times a loop has been executed? c++ How to count how many times a loop has been executed my code doesn't work as I expected it,
find the primes numbers before n number input by user and display them and count how many
numbers are in total
ex.
number input lets say 7,
and there are 3 numbers before 7
so it displays 2,3,5,7 and there are 3 prime numbers before 7
#include <iostream>
using namespace std;

int main()
{

 int n, i, k;
 int counter = 0;
 bool isprime;

 cout << "Enter a positive integer n: ";

 cin >> n;

 for(int k = 2; k <= n; k++)
 {
        isprime = true;

        for(int i = 2; i <= k - 1; i++)
            if(k%i == 0)
        {
                isprime = false;
        }

        if(isprime)
        cout << k << "\t";}

cout << "\nThere are " << counter << " primes less than " << n;
  return 0;
}

A: In your example, counter is never modified from its initial value. Try having it count what you want to count.
Added: ...
BTW. Prefer
for (i = 0; i < n; ++i)

for looping. The "i < n" is more idiomatic (easier to read) and the ++i normally will be more efficient than i++.

A: #include<iostream>
#include<string>
#include<cmath>

using namespace std;

int main()
{
    int num;
    int count = 0;

    cout << "Enter your range: ";
    cin >> num;

    for(int i = 1; i <= num; i++)
    {
        count = 0;
        for(int j = 2; j <= sqrt(i); j++)
        {
            if(i % j == 0)
            {
                count++;
                break;
            }
        }
        if(count == 0 && i != 1)
            cout << i << "   ";
    }
    cout << endl;
}

This will increase the count variable every time there's a prime number.

A: #include <iostream>
using namespace std;

int main()
{

 int n, i, k;
 int counter = 0;
 bool isprime;

 cout << "Enter a positive integer n: ";

 cin >> n;

 for(int k = 2; k <= n; k++)
 {
        isprime = true;

        for(int i = 2; i <= k - 1; i++)
            if(k%i == 0)
        {
                isprime = false;
        }

        if(isprime)
        {
            cout << k << "\t";
            counter++;
        }
 }

cout << "\nThere are " << counter - 1<< " primes less than " << n;

  return 0;
}

A: As said above counter is not incremented.
You should make a function
isPrime?(int n)
{
    int sqrt_n = sqrt(n)
    for(int i = 2; i <= sqrt_n; i++){ //You could check only to sqrt(n)
    if(n%i == 0)
    {
            return false;
    }
    }
return true;
}

And then you could use that function as follow:
int main()
{

 int n, i, k;
 int counter = 0;

 cout << "Enter a positive integer n: ";

 cin >> n;

 for(int k = 2; k <= n; k++)
 {
    if(isPrime?(k)) {
       counter++;
       cout << k << "\t";
    }
cout << "\nThere are " << counter << " primes less than " << n;
  return 0;
}


text:
Q: MCSession multipeer in background I am sending through multi peer in ios7 a file using this method:
_progressSend = [session sendResourceAtURL:imageUrl withName: info toPeer:peerID withCompletionHandler:^(NSError *error) {
    // Implement this block to know when the sending resource transfer completes and if there is an error.
    if (error) {
        NSLog(@"Send resource to peer [%@] completed with Error [%@]", peerID.displayName, error);
    }
    else {
        // Create an image transcript for this received image resource

    }
}];

The problem is very strange. This is what happens:
The device starts sending the resource, the progress bar starts filling up. When I put the app in the background, and check my email for example, the transfer is still going on (I can see that from the progress bar of the other device). If the transfer has finished, and I go back in the app, everything works just fine, but if I enter the app while the resource is still being transferred (for e.g. I exit 1/3 of the way and open it at 2/3) the app freezes completely and needs to be closed from the multitask bar. But Xcode doesn't show a crash. It is as iff the app keeps running but the user interface is just totally frozen. Does anyone have an idea??

A: Have you tried wrapping your code that sends the data in a dispatch_async block?
That might help.
Also how do you get the imageurl? Maybe it somehow can't be read when leaving and then re-entring you app

A: I had this issue also in a different type of way.  On the portion of code that updates the progress bar you need to make it call the main thead by putting the code inside this block:
dispatch_async(dispatch_get_main_queue(), ^{
//insert progress bar code here
});

I don't know why this happens but this seems to have fixed it for me.


text:
Q: Check if first column has 4 digits and if not pad with zeroes I'd like to check if the first column has 4 digits, and if not then add 0 in front so all should be 4 digits (using awk, bash, etc.):
T12FT 19/11/19 2000
T12FT 18/12/19 2040

T5 19/11/19 2000
T5 18/12/19 2080

T0015 19/11/19 2050
T0015 18/12/19 2060

I'd like to get following output:
T0012FT 19/11/19 2000
T0012FT 18/12/19 2040

T0005 19/11/19 2000
T0005 18/12/19 2080

T0015 19/11/19 2050
T0015 18/12/19 2060

How can I do that?

A: You could do it with sed:
sed -E '
    s/[[:digit:]]/000&/
    s/[[:digit:]]*([[:digit:]]{4})/\1/
' infile

The first substitution inserts 000 in front of the first digit in the line, so the intermediate state is
T00012FT 19/11/19 2000
T00012FT 18/12/19 2040

T0005 19/11/19 2000
T0005 18/12/19 2080

T0000015 19/11/19 2050
T0000015 18/12/19 2060

The second substitution then retains the last four digits of the first group of digits:
T0012FT 19/11/19 2000
T0012FT 18/12/19 2040

T0005 19/11/19 2000
T0005 18/12/19 2080

T0015 19/11/19 2050
T0015 18/12/19 2060


text:
Q: jQuery: changing link text on success In showComments (), an ajax call and on success i tried:
$('#showCommentLink').text("Hide");

Im trying to change the text from show all comments to "hide" without results.
Show all $isThereAnyComments comments

Have i missed something?

A: $('.showCommentLink') not $('#showCommentLink').
The # selector is for IDs, and the . selector is for classes.

A: $('.showCommentLink').text("Hide");

You used #, which looks for an id. "." looks for a class.
Also, you should read up on onobtrusive javascript - running that function in your href kind of defeats a major purpose of jquery!


text:
Q: Delphi how to implement OnAfterMonitorDpiChanged I am using a subclass TMyForm = class( tForm ) for all my forms.
I do not want to add the same code in all my forms and would like to override the OnAfterMonitorDpiChanged and add the common code into TMyForm.
How I can do that?
Or do I have to use
procedure WMDpiChanged(var Message: TWMDpi); message WM_DPICHANGED; ?
Delphi 10.3.3


text:
Q: "Authorization Required" screen when attempting to submit a Case via an VF Site Page I have an externally available site configured.
We use it as our web-to-case solution.
When using the copy on our production instance it works fine, but when attempting to have someone outside the system put in a ticket via the sandbox instance it ends up not working correctly, providing the Authorization Required force.com page instead.
Is this a glitch with my code, or a feature of the sandbox instance?

A: You should add the Visualforce page in your site's Public Access Setting.


text:
Q: Jenkins library: How to use one library in another one I have two different libraries, a common one CommonLib and a project specific one ProjectLib. They are loaded dynamically in the Jenkinsfile as follows.
library identifier: 'CommonLib@master', retriever: modernSCM(
[$class: 'GitSCMSource',
     remote: 'https://bitbucket.intra/scm/common/pipeline-helper.git',
     credentialsId: 'bitbucket.user'
])
library identifier: 'ProjectLib@master', retriever: modernSCM(
[$class: 'GitSCMSource',
   remote: 'https://bitbucket.intra/scm/project/jenkins-pipeline-helper-project.git',
   credentialsId: 'bitbucket.user'
 ])

Now in the vars (vars\test.groovy) of the ProjectLib, I have a function which shall call a function from the commonLib (vars\runPowershellResScript.groovy). My try is as follows:
def call() {
    library 'CommonLib'
    runPowershellResScript('ch/mycompany/common/scripts/test.ps1', "-homeDir 'd:\\projectxy")
}

Unfortunately this does not work as I expect and this error.
No library named CommonLib found

How can I use a dynamically loaded library within another?


text:
Q: (ASP.NET JAVASCRIPT and C#) Hide result of javascript calling C# method I am trying to hide the result of a C# method which is called from my javascript code in my aspx file. When I view the page source I want to return value, presently 'HI_MOM!', to not be visible.
My ASPX:

    <title>Hide Me</title>

My C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TestTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string magic()
    {
        return "HI_MOM!";
    }
}

Source Code after Running:

    <title>Hide Me</title>

Basically, I want to make it so that when I view the source code for the page the line "var url = HI_MOM!;" is not visible to the user or is masked in some way.
EDIT:
ANSWER: (with thanks to @Shadow Wizard for pointing me in the right direction)
In TestTest.aspx:

.
.
.
 jQuery.ajax({
    type: 'POST',
    url: 'TestTest.aspx/magic',
    cache: false,
    data: '{}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'text',
    success: function (msg) {
        var result = eval('(' + msg + ')');
        result = eval('('+result["d"]+')');

        //do something with your string =]
    }
 });

In TestTest.aspx.cs:
[WebMethod]
    public static string magic()
    {
        return "HI_MOM!";
    }

A: var url = <%= "'" + magic() + "'"%>;

A: Everything you want to run as javascript will be viewable to the user. You could make it look less obvious what it is doing or even go as far as encrypting it, but it's still all there in the browser.
The only way to truly hide this would be to do it all server side.

A: You will have to use AJAX for this.
Using jQuery is one option, with this you can turn magic to be Page Method then consume it.


text:
Q: It seems that using **even** sounds more idiomatic and natural in lots of situations, is it true? Consider these 2 sentences

Alice's cooking is so bad that her dog doesn't want to eat it.
Alice's cooking is so bad that
  even her dog doesn't want to eat it.

The latter sounds more idiomatic and natural, right?
It seems that using even sounds more idiomatic and natural in lots of situations, is it true?

A: even is not idiomatic. It adds a new information.
Without even, we only know that her dog doesn't want to eat her cooking. We have no information if she has tried to offer her cooking to other animals or persons.
With even, we know/assume that there have been several/many attempts to offer her cooking but nobody wanted to eat it. Each offeree was picky to some (different) extent. But no-one wanted to eat it. Neither the least picky one (her dog).
This would be a neutral understandig of facts in the second sentence. But the second sentence can also be used as an offense. In truth, there have been no attempts to offer her cooking to anyone (besides the speaker perhaps). Nevertheless, the speaker wants to present her cooking as unfavourably as possible and pretends/implies that such attempts have taken place with the result that no-one accepted her cooking. Neither her dog.

A: The sense of the sense of the sense of the


text:
Q: curl on Windows: "GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)" I want to access a service that uses Kerberos authentication. The service admin gave me a spnego.service.keytab file for the correct Kerberos principal and realm. I can run kinit against that keytab file to get a Kerberos ticket successfully. But when I try to access that service using curl in a Windows 7 laptop outside the cluster I get this error:
org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

The service happens to be Livy but a colleague gets the same error using Oozie on the same cluster so I don't think the details of the service itself matters much.
Here are the full details:
>curl --negotiate -u : http://<livy_server_host>:<port>/sessions/

<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 403 </title>

HTTP ERROR: 403

Problem accessing /sessions/. Reason:

    org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

Powered by Jetty://

What needs to be done to make the curl command work?

A: The Windows 7 laptop must be part of the same Kerberos realm in which the keytab was generated from.  The encryption used by the keytab and the service must also be supported by the Windows 7 laptop.  Curl is not a native Windows command, so you must import the supporting encryption libraries onto the Windows 7 laptop in order to make Curl work.


text:
Q: Cannot inject Worker using @WorkerInject I'm trying to inject data into my Worker, but the @WorkerInject is giving me an unresolved reference.
Bear in mind I have these defined in my gradle:
def hilt_version = '2.38.1'
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
    def hilt_worker_version = '1.0.0'
    implementation "androidx.hilt:hilt-work:$hilt_worker_version"
    kapt "androidx.hilt:hilt-compiler:$hilt_worker_version"

And this is my Worker class:
class MyWorker @WorkerInject constructor(
    @Assisted val context: Context,
    @Assisted workerParams: WorkerParameters
) :
    Worker(context, workerParams) { ... }

A: There's a new way to annotate this class:
@HiltWorker
class MyWorker @AssisstedInject constructor(
    @Assisted val context: Context,
    @Assisted workerParams: WorkerParameters
) :
Worker(context, workerParams) { ... }


text:
Q: Get content between two tags and then return full string how can i get some text between each two tags(<tagname></tagname>) and after changed the text of these two tags i need the complete string along with changes.think,this is the java string content.
before change

"Lorem ipsum dolor <tagname>text to be changed 1</tagname> amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <tagname>text to be changed 2</tagname> laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint <tagname>text to be changed 3</tagname> cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

after changed, should be like this

"Lorem ipsum dolor <tagname>text changed 1</tagname> amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <tagname>text changed 2</tagname> laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint <tagname>text changed 3</tagname> cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

actually i need a method like this,
String getChangedString(String toBeChanged){
   //process
   return changedString;
}

how can i get this.
thanks.

A: String getChangedString(String toBeChanged){
   String changedString = toBeChanged;

   while (changedString.indexOf("<tagname>") >= 0)
   {
     changedString = changedString.substring(0, changedString.indexOf("<tagname>")) +
       "whatever replacement string" +
       changedString.substring(changedString.indexOf("</tagname>") + "</tagname>".length());
   }

   return changedString;
}

A: Assuming that the tags are within an XML file, you should use one of the existing XML parsers such as DOM or SAX instead of reinventing the wheel.

A: I was looking for the same, maybe this question can help you, take a look:
Java regex to extract text between tags
It uses a regular expression to get the text content between tags. In my case, I was interested on getting the text from the first tags found on my xml, not from each tags

A: There is a flawless string parsing based utility available in org.apache.commons.lang.StringUtils, below code worked perfectly for me.
String title = StringUtils.substringBetween(testHtml, "<title>", "</title>");
System.out.println("title:" + title); // good


text:
Q: Parsing JSON in an Elixir/Phoenix application, not inside a controler or model, but from "/lib" I have a Phoenix/Elixir application. And I have a module in the "lib" folder in which I want to parse JSON. If it was in a controller or model, it'd be easier to do. But in the "lib" I don't have access to all those helper modules, do I? Then how can I do that? I need actually parse it in a just struct for which I don't have no model. I've looked into Poison but it seemed to that in order to use it I'd have to have a model in which I'd have to include @derive [Poison.Encoder]. Whereas I don't have one, I just want to convert a JSON string into a struct, like this:
" "\{"\"\a\": 123, "\b\": 456 "\}"\ "  ===> %{a: 123, b: 456}

How can I do that?
update
j_str = "{\"text\":\"changed readme fad996e98e04fd4a861840d92bdcbbcb1e1ec296\", \"user_name\":\"name123\"}"
Poison.Parser.parse!(~s(j_str)) # => ** (Poison.SyntaxError) Unexpected token at position 0: j

# or
Poison.decode!(~s|j_str|) # the same error

A: You can use Poison.Parser.parse!/1 for this purpose:
iex> str = "{\"text\":\"changed readme fad996e98e04fd4a861840d92bdcbbcb1e1ec296\", \"user_name\":\"name123\"}"

iex> Poison.Parser.parse!(str)
%{"text" => "changed readme fad996e98e04fd4a861840d92bdcbbcb1e1ec296",
  "user_name" => "name123"}

Note that this will parse keys as strings, not as atoms like in your example. The reason behind this is that there is no garbage collection for atoms in Erlang/Elixir. It is possible to convert keys to atoms with Poison, but this is strongly discouraged: you might hit the max number of atoms limit in the VM, which would crash the entire VM. So the general advice is to just stick with string keys unless you know exactly what you're doing.

A:
I need actually parse it in a just struct for which I don't have no model.

You don't need to have an Ecto model in order to use @derive [Poison.Encoder]; you can add it to plain structs as well:
defmodule AB do
  @derive [Poison.Encoder]
  defstruct [:a, :b]
end

and then do:
Poison.decode!(~s|{"a": 123, "b": 456}|, as: %AB{}) #=> %AB{a: 123, b: 456}`

From your code snippet, it looks like you may want a Map as output? You can do that by just calling Poison.decode!/1 with the string:
Poison.decode!(~s|{"a": 123, "b": 456}|) #=> %{"a": 123, "b": 456}


text:
Q: How can I get onKeyPress to give me the last key input with a Braille Display on iOS? I deleted the previous version of this question because it was all over the place. Sorry about that. I am using React Native. The issue I am having is that when using a Braille Display (Orbit Reader 20) to input letters into a TextInput field on iOS I get a concatenated string of all the character and not the last one I entered. I have tried this on Android as well, but on Android, it works the way I want it to. iOS will behave like Android, but only if I have focus on the onscreen keyboard and not on the actual input field.
Descriptions of the problem (all letters are typed with a braille display): I have focus on the input area, I type in the letter 'b'. In the input area, the letter 'b' appears which is what I want to happen. Next, I type in the letter 'c' which on Android will give me just the letter 'c', but on iOS I get the string "bc" which I get the key using keyPress.nativeEvent.key. It seems like iOS is not respecting the maxLength prop when input comes from the braille device.
What I have tried: I have tried to just cut the last letter off of the key by using keyPress.nativeEvent.key.slice(-1) which does give the single letter, but it messes with VoiceOver and TalkBack (example: 'a' is displayed in the text area then I type 'b' and the phone says "ab"). I have found that if I clear the input area using textInput.current.clear() when onChangeText is triggered it will give me the results I want in that keyPress.nativeEvent.key will give me the last letter, but it will clear out my text immediately and cuts off VoiceOver.
Code Snippet (this is the code for my custom TextInput component and just has some console.log statements so that I can see what is going on.):

import React, { useState, useRef } from 'react';
import { View, StyleSheet, TextInput } from 'react-native';

const BrailleInput = props => {
    const textInput = useRef();
    const [valueLetter, setValueLetter] = useState('');

    const handleInput = input => {
        console.log("onChangeText: " + input);
    };

    const handleClear = keyPress => {
        setValueLetter(keyPress.nativeEvent.key);

        console.log("onKeyPress: " + keyPress.nativeEvent.key);
    };

    return (
        <View style={props.style}>
            <TextInput
                ref={textInput}
                style={styles.textInput}
                maxLength={1}
                autoCorrect={false}
                autoFocus={true}
                onKeyPress={handleClear}
                onChangeText={handleInput}
                value={valueLetter}
                caretHidden={true}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    textInput: {
        height: '50%',
        width: '100%',
        borderColor: '#ffec33',
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 4,
        color: '#ffec33',
        textAlign: 'center',
        fontSize: 40
    },
});

export default BrailleInput;

Output:
iOS:
onKeyPress: a
onChangeText: a
onKeyPress: Backspace
onChangeText:
onKeyPress: ab
onChangeText: a

Android:
onKeyPress: a
onChangeText: a
onKeyPress: b
onKeyPress: c

I want the iOS output to look more like the Android Output. For some reason, it gives me extra Backspace inputs for the iOS version which I think are the main reason VoiceOver is not working like I want.
In the end, all I want is to have accessibility focus on the TextInput area, have TalkBack/VoiceOver speak the single letter that I input then be able to type another letter in to replace the previous letter, rinse, repeat. I need an accessible solution to this I have already been able to make a non-accessible solution.


text:
Q: += с пре и пост-инкрементами Ну ладно, разобрали разные ситуации с инкрементами. А если добавить +=?
$a = 10;
$a += $a++;

21

$a = 10;
$a += ++$a;

22

$a = 10;
$a += $a++ + ++$a;

34

Также пока непонятным остается такое:
$a = 10;
$a = $a++ + $a++;

21

Особенно интересно: когда происходит пост-инкрементация: сразу после того, как берется значение или только когда вычисляется все выражение?
Зависит ли это от реализации интерпретатора? От какой-нибудь JIT-оптимизации?

A: Потестировал немного - у меня получилось, что вычисление пред/постинкремента идет строго слева направо перед вычислением выражения, а уже потом выражение считается по общим правилам. То есть вначале выполняются все инкременты с возвращением значения, потом из возвращенных значений собирается результат выражения. Тестирован на tutorialspoint, Online PHP и Ideone. Везде поведение интерпретатора PHP было одинаковым.


text:
Q: Storing an encrypted cookie with Rails I need to store a small piece of data (less than 10 characters) in a cookie in Rails and I need it to be secure. I don't want anybody being able to read that piece of data or injecting their own piece of data (as that would open up the app to many kinds of attacks). I think encrypting the contents of the cookie is the way to go (should I also sign it?). What is the best way to do it?
Right now I'm doing this, which looks secure, but many things looked secure to people that knew much more than I about security and then it was discovered it wasn't really secure.
I'm saving the secret in this way:
encryptor = ActiveSupport::MessageEncryptor.new(Example::Application.config.secret_token)
cookies[:secret] = {
  :value => encryptor.encrypt(secret),
  :domain => "example.com",
  :secure => !(Rails.env.test? || Rails.env.development?)
}

and then I'm reading it like this:
encryptor = ActiveSupport::MessageEncryptor.new(Example::Application.config.secret_token)
secret = encryptor.decrypt(cookies[:secret])

Is that secure? Any better ways of doing it?
Update: I know about Rails' session and how it is secure, both by signing the cookie and by optionally storing the contents of the session server side and I do use the session for what it is for. But my question here is about storing a cookie, a piece of information I do not want in the session but I still need it to be secure.

A: *

*Setting a secure cookie
cookies.signed[:secret] = {
 :value => "foo bar",
 :domain => "example.com",
 :secure => !(Rails.env.test? || Rails.env.development?)
}

*Accessing the cookie
cookies.signed[:secret] # returns "foo bar"

The cookie is signed using ActionController::Base.cookie_verifier_secret. You can set the cookie_verifier_secret in the initializer file.

A: As KandadaBoggu says, it looks like what you want is a session variable, and session variables are by default encrypted and stored in cookies. However, if you have a look at the contents of config/initializers/session_store.rb you will find something like the following:
 # Be sure to restart your server when you modify this file.
 MyRailsApp::Application.config.session_store :cookie_store, :key => '_my_rails_app_session'

 # Use the database for sessions instead of the cookie-based default,
 # which shouldn't be used to store highly confidential information
 # (create the session table with "rails generate session_migration")
 # MyRailsApp::Application.config.session_store :active_record_store

Which suggests to me that you should use the database for sessions instead of the cookie-based default, which shouldn't be used to store highly confidential information. The pre-cooked migration makes everything really easy to set up so there's very little overhead in doing so, and once it's done there's basically zero overhead if you need to add a new piece of secret information at a later date!

A: I'm re-posting JacobM's answer, that he deleted, because it was the correct answer and pointed me in the right direction. If he undeletes it, I'll delete this one and pick his as the best answer.

First of all, if you use encrypt_and_verify instead of encrypt it will
  sign the cookie for you.
However, when it comes to security, I always prefer to rely on
  solutions that have been vetted in public, rather than rolling my own.
  An example would be the encrypted-cookies gem.


text:
Q: Helm Nginx Ingress - how to specify External IP in "helm install" command I need to specify External IP that will be associated to Nginx service upon the Ingress Controller creation using the HELM install:
helm install nginx-ingress ingress-nginx/ingress-nginx -f internal-ingress.yaml
--set controller.nodeSelector."beta\.kubernetes\.io/os"=linux
--set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux

So I want to set statically EXTERNAL-IP address that can be seen upon this creation:
kubectl get services
NAME                                     TYPE          CLUSTER-IP   EXTERNAL-IP   PORT(S)                                     AGE

nginx-ingress-ingress-nginx-controller   LoadBalancer  10.0.36.81   10.33.27.35   80:31312/TCP,443:30653/TCP   5d

I need this because DNS configuration has already been set up for this IP and I would like to avoid this kind of configuration again.

A: You can add flag to installation command:
 --set controller.service.loadBalancerIP=XXXX

where XXXX is static EXTERNAL IP you want to use.
Remember that  IP needs to be regional and in the same region as the cluster.
See: external-ip-ingress-controller.


text:
Q: Why won't StackPanel put textblock on left and button on right in Silverlight? OK, I give up: what do I have to change to this StackPanel below so that it puts the:

*

*text on far left of form

*button on far right of form.

alt text http://tanguay.info/web/external/stackPanelLeftRight.png
<UserControl x:Class="TestData333.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border CornerRadius="10" Background="Yellow" Padding="20">
            <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
                <ScrollViewer Background="Beige"
                              Height="230"
                              Width="360">
                    <StackPanel>
                        <TextBlock x:Name="TheContent"
                           Foreground="Navy"
                           FontSize="14"
                           TextWrapping="Wrap"/>
                    </StackPanel>
                </ScrollViewer>

                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="ProgressIndicator" Text="Ready..."
                               HorizontalAlignment="Left"/>
                    <Button Content="Load Data"
                        Width="100"
                        HorizontalAlignment="Right"
                        Click="Button_Load"
                        Margin="0 5 0 0"/>
                </StackPanel>

            </StackPanel>
        </Border>
    </Grid>
</UserControl>

ANSWER:
Downloaded Silverlight 3 toolkit which has DockPanel, installed, referenced System.Windows.Controls, then following XAML:
<UserControl x:Class="TestData333.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border CornerRadius="10" Background="Yellow" Padding="20">
            <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
                <ScrollViewer Background="Beige"
                              Height="230"
                              Width="360">
                    <StackPanel>
                        <TextBlock x:Name="TheContent"
                           Foreground="Navy"
                           FontSize="14"
                           TextWrapping="Wrap"/>
                    </StackPanel>
                </ScrollViewer>

                <toolkit:DockPanel Margin="0 5 0 0">
                    <TextBlock toolkit:DockPanel.Dock="Left" x:Name="ProgressIndicator" Text="Ready..."
                               FontSize="12"
                               HorizontalAlignment="Left"/>
                    <Button toolkit:DockPanel.Dock="Right" Content="Load Data"
                        Width="100"
                        HorizontalAlignment="Right"
                        Click="Button_Load"/>
                </toolkit:DockPanel>

            </StackPanel>
        </Border>
    </Grid>
</UserControl>

alt text http://tanguay.info/web/external/silverlightDockPanel.png

A: Do you mean that you want the button aligned to the right of the form? If so, StackPanel won't do that. It's made to "stack things up" either horizontally or vertically.
I would suggest you try DockPanel:
<DockPanel>
    <TextBlock x:Name="ProgressIndicator"
               DockPanel.Dock="Left"
               Text="Ready..." />
    <Button DockPanel.Dock="Right"
            Content="Load Data"
            Width="100"
            Click="Button_Load"
            Margin="0,5,0,0" />
</DockPanel>

A: you could use dockpanel from toolkit or use grid with 2 columns. and have the content of the second column right aligned

A: I think Matt's approach it the best. Two alternatives though are to use a grid and align the content to the left and right or to just give the button a really large margin.

A: Reference should be:
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"


text:
Q: Convert Apache mod_proxy [P] to Nginx equivalent We have this working in Apache. You can see here.
The $request_uri
/h_32/w_36/test.jpg

needs to be routed to
/index.php/img/i/h_32/w_36/test.jpg

index.php will route the request to the img controller and i method, then process the image and return it. However, my MVC works off of the REQUEST_URI. So simply rewriting the url will not work. The REQUEST_URI needs to be modified.
You can see in the last location block that I pass in the modified REQUEST_URI, but Nginx is trying to open /var/www/vhosts/ezrshop.com/htdocs/h_32/w_36/test.jpg (see Error Logs below) and throwing a 404.
Shouldn't Nginx be trying to send it for processing to index.php?? Why the 404?
root /var/www/vhosts/example.com/htdocs;
index index.php index.html;

set $request_url $request_uri;

location ~ (h|w|fm|trim|fit|pad|border|or|bg)_.*\.(jpg|png)$ {
    if ($request_uri !~ "/img/i/") {
            set $request_url /index.php/img/i$1.$2;
    }

    try_files $uri $uri/ /index.php/img/i$1.$2;
}

location / {
        try_files $uri $uri/ /index.php$uri?$args;
}

location ~ ^(.+\.php)(.*)$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  CI_ENV production; #CI environment constant
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_param  REQUEST_URI $request_url;
}

Error Logs:
Log 1:
/img/i/ does not match /h_32/w_36/test.jpg, request: GET /h_32/w_36/test.jpg HTTP/1.1

Log 2:
open() "/var/www/vhosts/ezrshop.com/htdocs/h_32/w_36/test.jpg" failed (2: No such file or directory), request: "GET /h_32/w_36/test.jpg HTTP/1.1"

A: Here's the solution.
root /var/www/vhosts/example.com/htdocs;
index index.php index.html;

location ~ ^/(h|w|fm|trim|fit|pad|border|or|bg)_.*\.(jpg|png)$ {
    include fastcgi_params;
    # route to /img/i/
    fastcgi_param REQUEST_URI /img/i$uri;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    fastcgi_param CI_ENV production; #CI environment constant
    fastcgi_pass  127.0.0.1:9000;
}

location / {
    try_files $uri $uri/ /index.php$uri?$args;
}

location ~ ^(.+\.php)(.*)$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  CI_ENV production; #CI environment constant
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include fastcgi_params;
}

A: I would use the following approach:
location ~* ^/_img/(h|w|fm|trim|fit|pad|border|or|bg)(_.+\.)(jpg|png)$ {
    try_files $uri $uri/ /index.php/img/i/$1$2$3?$args;
}

We use the regex in the location directive to capture the parts we want into the variables, and then we use those variables for the rewrite.
Since the location regex is defined in such a detailed way, it won't match the rewritten location. However, here we pass the changed URL directly to try_files.


text:
Q: Who is moving and with who's relation? What if we are in a cube of 3×3 m  which is further enclosed in a sphere of radius 50 m? And the sphere start to rotate on its own axis would we experience force?
If not then what happens if there is a window in the cube and there's nothing else which we can take to reference?

A: Rotation is absolute, only uniform paths are inertial. So the answer is yes, the rotating object (which is the sphere in your example) would experience force. The cube would experience no force at all since it is the sphere which is rotating. 1


text:
Q: Grouping dates in Big query I've been trying to write a query on big query to get the difference between two times (Created at and resolved at) and get the average of it grouped by day.
This is the query I wrote:
SELECT
    avg(datetime_diff(datetime(stats.resolved_at), datetime(created_at), HOUR)) as Difference,
    date(tickets.created_at)
FROM fresh_desk.tickets
WHERE
    type = "Revision Request"
    OR type = "Proof request"
    AND stats.first_responded_at is NULL
GROUP BY date(tickets.created_at)

The results are showing by date itself but when I'm building charts over this data on a BI tool, I'm getting the results with date grouped by timestamp as well. How can I avoid this to have the date grouped by day and nothing else? It should show average by day.

A: Another way to write this query could be
with T as (
  SELECT
    datetime_diff(datetime(resolved_at), datetime(created_at), HOUR) as Difference,
    date(created_at) as custom_date
FROM fresh_desk.tickets
WHERE
    type = "Revision Request"
    OR type = "Proof request"
    AND first_responded_at is NULL
GROUP BY date(created_at)
)

Select avg(Difference), custom_date from T group by custom_date

After getting the results you can use Datastudio to get a preview of your data and you can customize the chart to plot the custom_date (axis X)and the difference (axis Y)
If your current tool is using another data type for axis X, you should verify the type used by your tool when importing the data


text:
Q: how to add row in datagrid dynamically I am using WPF application
in this form have one gridview and one button
i am using the ObservableCollection have Generic and one class code like this
public partial class MainWindow : Window
{
        public ObservableCollection<gm> data1 = new ObservableCollection<gm>();
        public MainWindow()
        {
            InitializeComponent();
        }
      //  public ObservableCollection<gm> data { get { return data1; } }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {

           data1.Add(new gm() { no = 2, name = "vipul" });
           dataGrid1.ItemsSource = data1.ToArray();
        }
    }
    public class gm
    {
        public int no { get; set; }
        public string name { get; set; }
    }
}

when i am execute above code it add blank row in datagrid
please give me solution of this problem
i want to know how to add row in datagird run time.
thanks in advance

A: set autogeneratecolumns to true and just set data1 as itemssource
xaml
 <DataGrid x:Name="dataGrid1" AutoGenerateColumns="True" />

EDIT: to get the power of WPF look into DataBinding/MVVM

A: XAML is like this:
<DataGrid ItemsSource="{Binding}" />

code behind is this:
public MainWindow()
{
    InitializeComponent();
    DataContext = data1;
}

and remove this line:
dataGrid1.ItemsSource = data1.ToArray();

A:  data1.Add(new gm { no = 2, name = "vipul" }); // Remore ellipsis around gm.

In XAML just check the following that

*

*You have DataSource of your datagrid to {Binding Path="data1"}

*DataColumn of no have binding to {Binding Path="no"}

*DataColumn of name have binding path to {Binding Path="name"}


text:
Q: HTTPWebRequest with gzip compression How can I activate the gzip compression if i get my json data from a webservice?
Here is my code:
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
WebResponse response = await request.GetResponseAsync();

How can I set the Accept-Encoding in the HTTP Header?

A: Set the AutomaticDecompression property of the request to GZip:
request.AutomaticDecompression = DecompressionMethods.GZip;

(you can also set it to a combination of GZip and Deflate if you want to accept both)

EDIT: in WinRT, this property is not available. But anyway, in WinRT you should use the HttpClient class rather than HttpWebRequest. The AutomaticDecompression property is available on the HttpClientHandler class:
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
var client = new HttpClient(handler);


text:
Q: A button that linked 2 buttons together with a line (Tkinter) I had made another new change. Now it can sometimes draw lines between the buttons when I double clicked but it seems that it does not works the way that I intended too. Like I can connect any button when I clicked the 'Add line' button but instead it's kind of buggy. Sometimes it registered my double click and sometimes when I clicked button 1 and 5 and it connects 2 and 3 instead. So how can I do like, it will connect Button 2 and 3 when I only double clicked Button 2 and 3.
from tkinter import *
import tkinter

counter = 1
undone = []

numcount = 1

def drag_start(event):
    widget = event.widget
    widget.startX = event.x
    widget.startY = event.y

def drag_motion(event):
    global x, y
    widget = event.widget
    x = widget.winfo_x() - widget.startX + event.x
    y = widget.winfo_y() - widget.startY + event.y
    widget.place(x = x, y = y)

def add_button():
    global btn
    btn = Button(canvas, text = 'Button ' + str(numcount))
    btn.pack(side = tkinter.TOP, anchor = tkinter.NW)
    btn.bind('<Button-1>', drag_start)
    btn.bind('<B1-Motion>', drag_motion)

def draw_line(event):
    global click_number
    global x1, y1
    if click_number == 0:
        x1 = x
        y1 = y
        click_number = 1
    else:
        x2 = x
        y2 = y
        canvas.create_line(x1, y1, x2, y2, width = 2, tag = 'line')
        click_number = 0

def add_line():
    btn.bind('<Double-Button-1>', draw_line)

def num():
    global numcount
    numcount += 1
    add_btn.config(text = 'Add Button')

def func(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func

main = Tk()

main.title('Drag and Drop')
main.geometry('500x500')
canvas = Canvas(main, width = 500, height = 500, background = 'white')
canvas.pack(expand = YES, fill = BOTH)
click_number = 0

add_btn = Button(main, text = 'Add Button', command = func(add_button, num))
add_btn.place(x = 400, y = 10)

line_btn = Button(main, text = 'Add line', command = add_line)
line_btn.place(x = 400, y = 40)

main.mainloop()


text:
Q: Diaplay image issue I have a picture box (picture box 1) and in that box have drawn a rectangle and displayed the drawn portion using another picture box (picture box 2). Problem is when i draw rectangle (in picture box 1)the picture box 2 will not shows up but when change the position of the form (move the form) the picture box 2 shows up.
How to display the drawn potion...
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Pen pen = new Pen(Color.Green, 2))
    {
        pen.Color = Color.Red;
        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

        e.Graphics.DrawRectangle(pen, rect);

        foreach (Rectangle r in rectangles)
        {
            label1.Top = r.Top; label1.Left = r.Left; label1.Width = r.Width;
            label1.Height = r.Height;
            e.Graphics.DrawRectangle(pen, r);
            e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), r);
        }
    }

    if (!(rect.Width <= 0 | rect.Height <= 0))
    {
        sz1.Width = rect.Width * Convert.ToInt16(1.5);
        sz1.Height = rect.Height * Convert.ToInt16(1.5);
        pictureBox2.Size = sz1;
        w.X = 500; w.Y = 20;
        pictureBox2.Location = w;
        Bitmap niv = new Bitmap(pictureBox2.Width, pictureBox2.Height);
        using (Graphics g1 = Graphics.FromImage(niv))
        {
            g1.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g1.DrawImage(pictureBox1.Image, pictureBox2.ClientRectangle, rect, GraphicsUnit.Pixel);
        }

        pictureBox2.Image = niv;
        pictureBox2.Visible = true;
        pictureBox2.Invalidate();
    }
}

A: You can paint or repainting your picturebox using the OnPaint event.

A: I got it. just right click on the picture box2 and selected "Bring to Front" option.