[Solved] How to out...
 
Notifications
Clear all

[Solved] How to output PHP function within HEREDOC string 'HTML code' block

0 Posts
1 Users
0 Likes
6 Views
0
Topic starter
sw123456 Asks: How to output PHP function within HEREDOC string 'HTML code' block
I have a wordpress plugin which, via a shortcode, outputs HTML via a HEREDOC string (EOD). For example:

Code:
<<<EOD
<div>
    <p>hi</p>
    $get_avatar($current_user->ID, 32) 
</div>
EOD;

My questions is, how can I run the get_avatar function, from within the HEREDOC string? The

tag contents displays but the PHP function output does not.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

Unreplied Posts

[Solved] How to configure CMakeLists.txt to install public headers of a shared library?

FrameBuffer Asks: How to configure CMakeLists.txt to install public headers of a shared library?
I want to use cmake to install my library edv but when I execute:

Code:
cmake --build . --target install

It installs but it only creates the bin/edv.dll and lib/ < empty >. How can I make cmake to install the EDV_PUBLIC_INCLUDE_DIRECTORIES inside an include/... ?

Here’s my CMakeLists.txt:

Code:
cmake_minimum_required(VERSION 3.12)

project(edv)

# include PUBLIC directories
set(EDV_PUBLIC_INCLUDE_DIRECTORIES      include/ )

set(EDV_PRIVATE_INCLUDE_DIRECTORIES     src/   )

# Edv source files list
file(GLOB_RECURSE EDV_SOURCE_FILES "src/*.cpp" "src/*.hpp*")


# build the library
add_library(${PROJECT_NAME} SHARED ${EDV_SOURCE_FILES} )

target_include_directories(${PROJECT_NAME} PUBLIC ${EDV_PUBLIC_INCLUDE_DIRECTORIES})
target_include_directories(${PROJECT_NAME} PRIVATE ${EDV_PRIVATE_INCLUDE_DIRECTORIES})

install (TARGETS ${PROJECT_NAME}
    RUNTIME DESTINATION bin
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib
    PUBLIC_HEADER DESTINATION include
)

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.
 
 
 

[Solved] Transform an SQL statement to Eloquent query builder

Anibal Cardozo Asks: Transform an SQL statement to Eloquent query builder
I have an SQL query that I find hard to translate it to a Laravel Eloquent query. I tried it with workbench and it works fine.

Code:
SELECT fi.id,fi.internal_name,fi.nombre_contacto,fi.apellidos_contacto,fi.category,
COALESCE(SUM(fi.totalClicks), 0) AS totalclicks FROM(

   SELECT af.id,af.internal_name,af.nombre_contacto,
            af.apellidos_contacto,af.category,SUM(afc.clicks) AS totalClicks
   FROM afiliados_referral_clicks afc, afiliados af WHERE  afc.idAfiliado = af.id
    and fecha >= DATE('2021-07-01') AND fecha<= DATE('2021-07-31')
   GROUP BY af.id 
UNION
SELECT af.id,af.internal_name,af.nombre_contacto,
        af.apellidos_contacto,af.category, 0 AS totalClicks 
FROM afiliados af   ) as fi
GROUP BY fi.id
LIMIT 7000
;

What did I try? I can see there are 3 SELECTs in the query, the outer one (parent).

Code:
SELECT fi.id,fi.internal_name,fi.nombre_contacto,fi.apellidos_contacto,fi.category,COALESCE(SUM(fi.totalClicks), 0) AS totalclicks 
FROM(somewhere as fi)

And two inner ones (child1).

Code:
SELECT af.id,af.internal_name,af.nombre_contacto,
            af.apellidos_contacto,af.category,SUM(afc.clicks) AS totalClicks
 FROM afiliados_referral_clicks afc, afiliados af WHERE  afc.idAfiliado = af.id
    and fecha >= DATE('2021-07-01') AND fecha<= DATE('2021-07-31')
 GROUP BY af.id 
UNION
something

child2

Code:
something
UNION
SELECT af.id,af.internal_name,af.nombre_contacto,
        af.apellidos_contacto,af.category,0 AS totalClicks

My approach was to make 3 separate queries and merge them.

child1

Code:
$child1 = $db->table($db::raw('afiliados, afiliados_referral_clicks'))
            ->whereColumn('afiliados.id','=','afiliados_referral_clicks.idAfiliado')
            ->addSelect(['afiliados.id','internal_name','nombre_contacto','apellidos_contacto'])
            ->selectRaw("COALESCE(SUM(clicks), 0) AS totalClicks")
            ->whereBetween('afiliados_referral_clicks.fecha',[$params['fechaReservaFrom'],$params['fechaReservaTo']])
            ->groupBy('afiliados.id')
            ;

child2

Code:
$child2 = $db->table('afiliados')
            ->addSelect(['id','internal_name','nombre_contacto','apellidos_contacto'])
            ->selectRaw("0 AS totalClicks")
            ;

The parent will unite both children.

Code:
$parent = $child1->union($child2)
        ->addSelect(['afiliados.id','afiliados.internal_name','afiliados.nombre_contacto','afiliados.apellidos_contacto'])
        ->selectRaw("COALESCE(SUM(totalClicks), 0) AS totalClicks")
        ->get()
        ;

But when executing the code I get this error.

400 (SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘totalClicks’ in ‘field list’

I think I’m on the right track though, if I return $child1->get() or $child2->get() I get the collections just fine, the issue I believe is in the $parent since I don’t know how to access the totalClicks column I added in $child2.

Of course, that’s what I tried, I could still have something horribly wrong, I hope you guys can help me.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Substituting a specific character at the end of words

MsBonniePython Asks: Substituting a specific character at the end of words

Code:
import re

text="Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder."
text=re.sub(r'r$b','rh',text)
print(text)

Desired output:

Her sweet-natured fatherh is constantly henpecked by his domineering wives, who rule theirh domains with iron fists. His wives were named Alexis, Eris, Irerh, Zenith and Saunderh.

Output:

Her sweet-natured father is constantly henpecked by his domineering wives, who rule their domains with iron fists. His wives were named Alexis, Eris, Irer, Zenith and Saunder.

I.e., no change has occurred in the string. Is something wrong?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] nltk_data installation gives RuntimeWarning

Tony Stark Asks: nltk_data installation gives RuntimeWarning

Code:
python3 -m nltk.downloader -d /usr/local/share/nltk_data all

Upon running the above command in GCP, I face the following RuntimeWarning

Code:
'nltk.downloader' found in sys.modules after import of package 'nltk', but prior to execution of 'nltk.downloader'; this may result in unpredictable behaviour

Also I’ve already installed nltk. And whilst installing that, I had to add the –proxy switch. I’m assuming I’d require a proxy switch over here too, so there’s a chance that might be the problem over here. But I’m unaware as to how I can add the proxy switch here.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] How to paste one picture on top of another into a defined region (Python, OpenCV)

Tina J Asks: How to paste one picture on top of another into a defined region (Python, OpenCV)
I have this simple Python code that captures video from the camera and makes predictions on the emotions of the face (took it from here in case you need to run it).

I like to put this video capture inside this frame (center is transparent) and display all. How can I do this?


enter image description here

Code:
import numpy as np
import argparse
import matplotlib.pyplot as plt
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# command line argument
ap = argparse.ArgumentParser()
ap.add_argument("--mode",help="train/display")
mode = ap.parse_args().mode

# plots accuracy and loss curves
def plot_model_history(model_history):
    """
    Plot Accuracy and Loss curves given the model_history
    """
    fig, axs = plt.subplots(1,2,figsize=(15,5))
    # summarize history for accuracy
    axs[0].plot(range(1,len(model_history.history['accuracy'])+1),model_history.history['accuracy'])
    axs[0].plot(range(1,len(model_history.history['val_accuracy'])+1),model_history.history['val_accuracy'])
    axs[0].set_title('Model Accuracy')
    axs[0].set_ylabel('Accuracy')
    axs[0].set_xlabel('Epoch')
    axs[0].set_xticks(np.arange(1,len(model_history.history['accuracy'])+1),len(model_history.history['accuracy'])/10)
    axs[0].legend(['train', 'val'], loc='best')
    # summarize history for loss
    axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])
    axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])
    axs[1].set_title('Model Loss')
    axs[1].set_ylabel('Loss')
    axs[1].set_xlabel('Epoch')
    axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)
    axs[1].legend(['train', 'val'], loc='best')
    fig.savefig('plot.png')
    plt.show()

# Define data generators
train_dir = 'data/train'
val_dir = 'data/test'

num_train = 28709
num_val = 7178
batch_size = 64
num_epoch = 50

train_datagen = ImageDataGenerator(rescale=1./255)
val_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
        train_dir,
        target_size=(48,48),
        batch_size=batch_size,
        color_mode="grayscale",
        class_mode='categorical')

validation_generator = val_datagen.flow_from_directory(
        val_dir,
        target_size=(48,48),
        batch_size=batch_size,
        color_mode="grayscale",
        class_mode='categorical')

# Create the model
model = Sequential()

model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))

# If you want to train the same model or try other models, go for this
if mode == "train":
    model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001, decay=1e-6),metrics=['accuracy'])
    model_info = model.fit_generator(
            train_generator,
            steps_per_epoch=num_train // batch_size,
            epochs=num_epoch,
            validation_data=validation_generator,
            validation_steps=num_val // batch_size)
    plot_model_history(model_info)
    model.save_weights('model.h5')

# emotions will be displayed on your face from the webcam feed
elif mode == "display":
    model.load_weights('model.h5')

    # prevents openCL usage and unnecessary logging messages
    cv2.ocl.setUseOpenCL(False)

    # dictionary which assigns each label an emotion (alphabetical order)
    emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}

    # start the webcam feed
    cap = cv2.VideoCapture(1)
    while True:
        # Find haar cascade to draw bounding box around face
        ret, frame = cap.read()
        if not ret:
            break
        facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5)

        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)
            prediction = model.predict(cropped_img)
            maxindex = int(np.argmax(prediction))
            text = emotion_dict[maxindex]

            if ("Happy" in text) or ("Sad" in text):
                cv2.putText(frame, text, (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)

        cv2.imshow('Video', cv2.resize(frame,(1600,960),interpolation = cv2.INTER_CUBIC))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] How to read an excel file where columns are repeated in a single row and convert them into datatable

Sunny Asks: How to read an excel file where columns are repeated in a single row and convert them into datatable
I need to import an excel sheet and read the data and add this data to the database in ASP.NET Core MVC.

My table looks like this:


enter image description here

when I have the data in excel this format:


enter image description here

I’m able to read and add the data to database.

But I my Excel sheet is filled like this:


this

where the date is Day and Score and CutOf is in the single column header and these are repeating in a single row.

So how to read and convert them into a row basis for each guy and add them to the database?

Code:
var dt = new DataTable();

//Checking file content length and Extension must be .xlsx
if (file != null && file.ContentType.Length > 0 && System.IO.Path.GetExtension(file.FileName).ToLower() == ".xlsx")
{
    //Create a Folder.
    string path = Path.Combine(hostingEnv.WebRootPath, "Uploads");
    
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    
    //Save the uploaded Excel file.
    string fileName = Path.GetFileName(file.FileName);
    string filePath = Path.Combine(path, fileName);

    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        file.CopyTo(stream);
    }
    
    using (var workbook = new XLWorkbook(filePath))
    {
        IXLWorksheet worksheet = workbook.Worksheet(1);
        bool FirstRow = true;

        //Range for reading the cells based on the last cell used.
        string readRange = "1:1";
        
        foreach (IXLRow row in worksheet.RowsUsed())
        {
            //If Reading the First Row (used) then add them as column name
            if (FirstRow)
            {
                //Checking the Last cellused for column generation in datatable
                readRange = string.Format("{0}:{1}", 1, row.LastCellUsed().Address.ColumnNumber);
                
                foreach (IXLCell cell in row.Cells(readRange))
                {
                    dt.Columns.Add(cell.Value.ToString());
                }
                
                FirstRow = false;
            }
            else
            {
                //Adding a Row in datatable
                dt.Rows.Add();
                int cellIndex = 0;
                
                //Updating the values of datatable
                foreach (IXLCell cell in row.Cells(readRange))
                {
                    dt.Rows[dt.Rows.Count - 1][cellIndex] = cell.Value.ToString();
                    cellIndex++;
                }
            }
        }
        
        //If no data in Excel file
        if (FirstRow)
        {
            ViewBag.Message = "Empty Excel File!";
        }

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] (react + express) DOM on server – Return web pages (SSR)

quertyqualified Asks: (react + express) DOM on server – Return web pages (SSR)
I have a problem related to rendering HTML from node js.

I am creating dynamic HTML (Reactj concept they are currently using), but I don’t know how to do it the same way Reactjs does on my node js server. Renderizando elementos – React

I used:

Code:
const express = require ('express')
const app = express ()
const port = 3000
// app.use (express.static ("public"))
app.listen (port, () => {
  console.log (`Example app listening at http: // localhost: $ {port}`)
})

I have read that if you use app.use (express.static .., it just loads static files.

So I decided to add an endpoint, to convert the site to dynamic:

Code:
app.get ("/", (req, res) => {
  res.send ("<html> <head> </head> <body> <h1> .... </h1> </body> </html>");
});

The problem is that I need to take an “index.html” pass it to plain text, read it with DOM and through the DOM add or remove elements (text) Finally return the entire html page.

Code:
1 - Pass the html to text.
2 - Cycle that text by dom
3 - Add or remove items
3.1 - Add divs inside other containers "through an id" by DOM

app.get ("/", (req, res) => {
  res.send (stringTextHtmlWebPage); 
// The problem is that I have to return the entire directory like 
// app.use(express.static ("public")) does; but with the modified file.
});

In Reactj they do something similar. They inject with the ReactDOM.render. They have a:

Code:
index.js
function App () {
  return (<div className = "container mt-5"> ... </div>);
  // I was surprised by this line, it goes without any quotes ... and it works ...
}

ReactDOM.render (
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById ('root') // element from public / index.html
);

Index.html
  <body>
    <noscript> You need to enable JavaScript to run this app. </noscript>
    <div id = "root"> </div>

In my case, how would it be to return an entire HTML page. With the steps that I indicated?

Edit:

I have to return a whole directory of files. (But some modified and some not) For instance: I modify the index.html but it has associated a css, js, bootstrap … It has to work like an “app.use (express.static (” public “));” but with some modified files. In short, modify a file using node js and then call app.use (express.static (“public”)); and that this file is modified. (Similar to what React does)

Code:
// Modify file
// calls app.use (express.static ("public")); (with the modification)

or would there be some way to inject the code into my “app” variable? Some of the style

Code:
app.injectPath ("public / index.html"). Tour_the_DOM (tag ["tag1"]) = "<div> add this div </div>";

Just like React does?

I can’t use templates (pug, manillar…), because the source code of the pages is written elsewhere.

I have also read: Agregar React a un sitio web – React But I don’t know how to integrate it with app.use (express.static (“public”))

This is what I am looking for. Representación del lado del servidor con React But it’s not working. Any solution to do the same?

Thanks in advance.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Function default argument value depending on argument name in C++

Fedor Asks: Function default argument value depending on argument name in C++
If one defines a new variable in C++, then the name of the variable can be used in the initialization expression, for example:

Code:
int x = sizeof(x);

And what about default value of a function argument? Is it allowed there to reference the argument by its name? For example:

Code:
void f(int y = sizeof(y)) {}

This function is accepted in Clang, but rejected in GCC with the error:

Code:
'y' was not declared in this scope

Demo: Compiler Explorer – C++

Which compiler is right here?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Create new words by replacing all occurrences by letter pair

GameAtrix Asks: Create new words by replacing all occurrences by letter pair
Im trying to write a function that loops over a string and replaces all the occurrences of one letter with another and create new words of all possible combinations. The letters that should replace each other are a pair. Like s and z or v and f and are hard coded. The combinations should work both ways, e.i sam -> zam and zed -> sed

The order of the words in the set are not important. For the pairs [s,z] and [v,f] the word stuffs should generate ztuffs, ztuvfs, ztuvfz, ztuffz, stuvvs, stuvvz, stuffz, stufvz. (I think thats all possible combinations, but i may have missed some)

I can’t get it to work and it feels like I’m missing something, maybe the function should be recursive in some way? Or there is something i miss?

First function I tried the more dynamic way by adding arrays of combinations and the latter it’s just if statements doing the checks.

This only replaces the first occurring letter in the set and not the other way around

Code:
console.log(replaceSimilarCharacters('stuffs')); // `[ 'stuffs', 'ztuffz', 'stuvvs' ]`

const replaceSimilarCharacters = (word) => {
  let letterCombination = [
    ['s', 'z'],
    ['f', 'v']

  ];
  const set = new Set();
  set.add(word); // original word
  for (let i = 0; i < word.length; i++) {
    letterCombination.forEach((letterCombo) => {
      letterCombo.forEach((letter) => {
        if (word[i] === letter) {
          const currentIndex = letterCombo.indexOf(letter);
          const nextIndex = (currentIndex + 1) % letterCombo.length;

          const nextLetter = letterCombo[nextIndex];
          const prevLetter = letterCombo[nextIndex - 1];
          const regex = new RegExp(letter, 'g');

          word = word.replace(regex, nextLetter);
          set.add(word);
          word = word.replace(regex, prevLetter);
          set.add(word);
        }
      });
    });
  }

  return Array.from(set);
};

This works a bit better but still missing some combinations

Code:
console.log(replaceLettersInWord('stuffs')); // `[ 'stuffs', 'ztuffs', 'stuvfs', 'stufvs', 'stuffz' ]`

const replaceLettersInWord = (word) => {
  const set = new Set();
  set.add(word);

  for (let i = 0; i < word.length; i++) {
    const currentLetter = word[i];

    if (currentLetter === 'z') {
      set.add(setCharAt(word, i, 's'));
    }
    if (currentLetter === 's') {
      set.add(setCharAt(word, i, 'z'));
    }
    if (currentLetter === 'f') {
     set.add(setCharAt(word, i, 'v'));
    }
    if (currentLetter === 'v') {
     set.add(setCharAt(word, i, 'f'));
    }
  }
  return Array.from(set);
};
const setCharAt = (str, index, chr) => {
  if (index > str.length - 1) return str;
  return str.substring(0, index) + chr + str.substring(index + 1);
};

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Powershell Set Lid Close Action

CraigJPerry Asks: Powershell Set Lid Close Action
I wanted to automate setting the action Windows 7 takes when the lid is closed on my work laptop, as this is reset via GPO every time i login.

I know that i can use the powercfg command in a batch script to achieve this:

Code:
powercfg -setacvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg -setdcvalueindex 5ca83367-6e45-459f-a27b-476b1d01c936 0

However, this was a good excuse to attempt learning some powershell. My first attempt takes over 10 seconds to run.

How can i improve on the below, both in terms of runtime & in terms of cleanliness of the code. What would be the idiomatic powershell way to approach the below?

Code:
$DO_NOTHING = 0

$activePowerPlan = Get-WmiObject -Namespace "rootcimv2power" Win32_PowerPlan | where {$_.IsActive}
$rawPowerPlanID = $activePowerPlan | select -Property InstanceID
$rawPowerPlanID -match '\({.*})}'
$powerPlanID = $matches[1]

# The .GetRelated() method is an inefficient approach, i'm looking for a needle and this haystack is too big. Can i go directly to the object instead of searching?
$lidCloseActionOnACPower = $activePowerPlan.GetRelated("win32_powersettingdataindex") | where {$_.InstanceID -eq "Microsoft:PowerSettingDataIndex$powerPlanIDAC{5ca83367-6e45-459f-a27b-476b1d01c936}"}
$lidCloseActionOnBattery = $activePowerPlan.GetRelated("win32_powersettingdataindex") | where {$_.InstanceID -eq "Microsoft:PowerSettingDataIndex$powerPlanIDDC{5ca83367-6e45-459f-a27b-476b1d01c936}"}

$lidCloseActionOnACPower | select -Property SettingIndexValue
$lidCloseActionOnACPower.SettingIndexValue = $DO_NOTHING
$lidCloseActionOnACPower.put()

$lidCloseActionOnBattery | select -Property SettingIndexValue
$lidCloseActionOnBattery.SettingIndexValue = $DO_NOTHING
$lidCloseActionOnBattery.put()

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

Share: