How to end FreeMarker processing prematurely in normal way? Posted: 10 Sep 2021 08:00 AM PDT I'd like to exit early from processing a FreeMarker template (to reduce indentation compared to wrapping a lot of code in a conditional). Like: <#if !precondition><#-- End processing --></#if> <#-- Do something if precondition met --> I've been reading through the docs for <#stop> which say This must not be used for ending template processing in normal situations! but unfortunately the docs forget to say what is the way to end template processing in normal situations. |
Rsquared Values for Complex Indicators in CFA Using Lavaan Posted: 10 Sep 2021 08:00 AM PDT I'm trying to find the Rsquared value for a complex indicator (an indicator that loads onto two factors) using Lavaan. Normally you can just square the standardized loading to get the Rsquared value or use the parameterestimates function. However, when I model an indicator as loading onto two factors parameterestimates only gives 1 rsquared value for the complex indicator. Is there a way to determine the variance explained from each of the factors? Here is my code: model <- ' field_belong =~ V8FBL1 + V8FBL2 + V8FBL3 + V8FBL4 + V8FBL5 + V8FID1 field_identity =~ V8FID1 + V8FID2 + V8FID3 ' fit <- cfa(model, data = ltfu, missing = "fiml") summary(fit, fit.measures = TRUE, standardized = TRUE) par_est <- parameterestimates(fit, rsquare = T) I am trying to get rsquared values for V8FID1 for both factors. Overall, I want to know the percent of variance explained in the V8FID1 variables by field_belong and field_identity separately. |
Cloud functions for multiples files gcp bucket events Posted: 10 Sep 2021 07:59 AM PDT I'm creating a Cloud Function in GCP to automatically resize images uploaded to a bucket and transfer them to another bucket. Since the images arrive in batches and one folder might contain hundreds or thousands of images, is it better to incorporate in the code the ability to deal with the multiple files or is better to let cloud functions be triggered on every image uploaded. |
Take an object from an array of objects based on the max value on one of its properties Posted: 10 Sep 2021 07:59 AM PDT Let's say I got an array of object like this a = [ {name: John, age: 15}, {name: Max, age: 17}, {name: Tom, age: 11}, ] How can I take just the object containing Max, 17? This would be the result b = [ {name: Max, age: 17} ] or better c = {name: Max, age: 17} |
How to display the logged in user details in a table format using session in node js , react js , sql? Posted: 10 Sep 2021 07:59 AM PDT This the view page where user details are redirected Hello all currently i am working on a project which has two form login and user details form. When users login and fills the details form after that it will redirect it to view page where he/she can view, edit ,delete his/her record. But when user login only his records should be seen. In my case it is fetching all the records in a view page. I am using session in node js. I don't know what's gone wrong. Server code const express = require("express"); const app = express(); const cors = require('cors'); const mysql = require("mysql"); const cookie=require("cookie-parser"); const session=require("express-session"); const bodyparser=require("body-parser"); app.use(cors({ origin:("http://localhost:3000"), methods:("GET","POST"), credentials:true })); app.use(cookie("secret")); app.use(bodyparser.urlencoded({extended:true})); app.use(session({ key:"userid", resave:false, saveUninitialized:false, secret:"userinfo", cookie:{ expires:60*60*24, }, })) app.use(express.json()); const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'demo' }); db.connect((err) => { if (err) { throw err; } else { console.log("Mysql Connected"); } }) //var sess app.post('/register', (req, res) => { const email = req.body.email; const password = req.body.password; const cpassword = req.body.cpassword; db.query("SELECT FROM registration WHERE email='"+email+"';", [email], (err, result) => { if(result){ res.send({message:"User already exists"}) } else{ db.query("INSERT INTO registration (email,password,cpassword) VALUES(?,?,?)", [email, password, cpassword], (err, result) => { if(err){ res.send(err); } else{ res.send({message:"Registered Successful"}) } }) } }) }) app.post("/login", (req, res) => { const email = req.body.email; const password = req.body.password; db.query("SELECT * FROM registration WHERE email='"+email+"' AND password='"+password+"';", [email,password], (err, result) => { if(err){ res.send({err:err}); } if(result.length>0){ req.session.user=result; console.log( req.session.user) res.send(result); // sess=req.session; // sess.userid=req.body.email; // console.log(req.session) else{ res.send({message:"Wrong username/passsword"}) } }) app.get("/login",(req,res)=>{ if(req.session.user){ res.send({loggedIn:true,user:req.session.user}) } else{ res.send({loggedIn:false}); } }) app.post('/add', (req, res) => { const firstname=req.body.firstname; const lastname=req.body.lastname; const email=req.body.email; const mobile=req.body.mobile; const address=req.body.address; const city=req.body.city; const pincode=req.body.pincode; const conference=req.body.conference; const seminar=req.body.seminar; const paper=req.body.paper; //const user_id=req.body.user_id; if(firstname==""||lastname==""||email==""||mobile==""||address==""||city==""||pincode==""||conference==""||seminar==""||paper=="") { return res.status(422).json({error:"Please Fill the form correctly"}); } db.query("INSERT INTO teacher (firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper) VALUES(?,?,?,?,?,?,?,?,?,?)", [firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper], (err, result) => { console.log(err) // if(result){ // //sess=req.session; // req.session.user=result; // console.log(req.session.user) // res.send(result) //sess.email=req.body.email; //if(sess.email){ //console.log( sess) //res.send(result) //res.redirect("/view"); //} // } // else{ // res.send(err) // } }) }) // }) // app.get("/teachersdata" , (req, res) => { db.query("SELECT * FROM teacher ",(err,result)=>{ if(result){ res.send(result); } }) app.get("/teachersdata/:id", (req, res) => { db.query('SELECT * FROM teacher WHERE id=?',[req.params.id], (err, result)=>{ if(err){ console.log('Error while fetching employee by id', err); }else{ res.send(result) } }) }) app.get("/logout",(req,res)=>{ console.log("logout page"); //req.logout() console.log( req.session.user) res.clearCookie("user") //res.redirect("/login") req.session.destroy((err) => { res.redirect('/login') // will always fire after session is destroyed }) }) }) app.put('/edit/:id',(req,res)=>{ const firstname=req.body.firstname; const lastname=req.body.lastname; const email=req.body.email; const mobile=req.body.mobile; const address=req.body.address; const city=req.body.city; const pincode=req.body.pincode; const conference=req.body.conference; const seminar=req.body.seminar; const paper=req.body.paper; const id=req.params.id; db.query("UPDATE teacher SET firstname=?,lastname=?,mobile=?,email=?,address=?,city=?,pincode=?,conference=?,seminar=?,paper=? WHERE id=?",[id,firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper],(err,res)=>{ if(err){ console.log(err) } else{ res.send(res); } }) }) app.delete("/delete/:id",(req,res)=>{ db.query("DELETE FROM teacher WHERE id=?",[req.params.id],(result,err)=>{ if(err){ res.send(err) } else{ res.send(result) } }) }) app.listen(3001) This is the react code import React from 'react'; import axios from 'axios'; import { useState,useEffect } from 'react'; import { Link } from 'react-router-dom'; export const View = () => { const [teacherList, setteacherList] = useState([]); useEffect(() => { loadUsers(); }, []) const loadUsers= async()=>{ const result =await axios.get("http://localhost:3001/teachersdata"); console.log(result) setteacherList(result.data) } const deleteUser = async id => { await axios.delete(`/delete/${id}`); loadUsers(); }; return ( <div> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">FirstName</th> <th scope="col">LastName</th> <th scope="col">Email</th> <th>Action</th> </tr> </thead> <tbody> { teacherList.map((user,index)=>( <tr> <th scope="row">{index+1}</th> <td>{user.firstname}</td> <td>{user.lastname}</td> <td>{user.email}</td> <td> <Link class="btn btn-primary me-md-2" to={`/teachersdata/${user.id}`}>View</Link> <Link class="btn btn-outline-primary me-md-2" to={`/edit/${user.id}`}>Edit</Link> <Link class="btn btn-danger" onClick={() => deleteUser(user.id)}>Delete</Link> </td> </tr> ))} </tbody> </table> </div> ) } I want that when user login and fills details form only his or logged in user details should be displayed each users should get their own details in the view page after login. I am new to node js and react. Thanks in advance |
Work with different tabs, of the Notebook tkinter Posted: 10 Sep 2021 07:59 AM PDT I have a question or problem, maybe there is an answer, but I still can't understand. I have an application, which works with several Notebook tabs Main When I click on any button, it calls me a function that in turn works with a class where it creates me, the tab and the widgets: def open_issuesDeviation (self): global deviation deviation = Deviation (self.root) self.book.add (deviation, text = 'Issues DEVIATIONS') self.book.select (deviation) deviation.DESVfr1_entModulo.focus () There is even great, I do my tasks I can open,. Tabs and work on them: Work with tabs My problem is that in the menu bar or in the contextual menu of the right click, when hitting search, call a simple function that does: def search (self, event): self.DESVfr1_entModulo.focus () Event CTRL+F, find It is to activate the focus in the entry, when opening each tab and doing CTRL F, or searching in the menu, it manages to activate the focus, the problem is when I return to a previous tab, this no longer works for me, and I have seen that It is because perhaps in each tab, it will be created with a different name to the widget: Tab 1: .! Deviation.! Labelframe.! Entry Tab 2: .! Deviation2.! Labelframe.! Entry I think I understand that the last tab is always active. I have seen that there is a lot of talk about link tags, and I think it may be the solution but I don't understand how I can implement it in my case. Thanks |
Python Iterate over rows and update SQL Server table Posted: 10 Sep 2021 07:59 AM PDT My Python code works to this point and returns several rows. I need to take each row and process it in a loop in Python. The first row works fine and does its trick but the second row never runs. Clearly I am not looping correctly. I believe I am not iterating over each row in the results. Here is the code: for row in results: print(row[0]) F:\FinancialResearch\SEC\myEdgar\sec-edgar-filings\A\10-K\0000014693-21-000091\full-submission.txt F:\FinancialResearch\SEC\myEdgar\sec-edgar-filings\A\10-K\0000894189-21-001890\full-submission.txt F:\FinancialResearch\SEC\myEdgar\sec-edgar-filings\A\10-K\0000894189-21-001895\full-submission.txt for row in results: with open(row[0],'r') as f: contents = f.read() bill = row for x in range(0, 3): VanHalen = 'Hello' cnxn1 = pyodbc.connect('Driver={SQL Server};' 'Server=XXX;' 'Database=00010KData;' 'Trusted_Connection=yes;') curs1 = cnxn1.cursor() curs1.execute(''' Update EdgarComments SET Comments7 = ? WHERE FullPath = ? ''', (VanHalen,bill)) curs1.commit() curs1.close() cnxn1.close() print(x) Error: ('HY004', '[HY004] [Microsoft][ODBC SQL Server Driver]Invalid SQL data type (0) (SQLBindParameter)') |
Reading documents from MongoDB with GoLang Posted: 10 Sep 2021 07:59 AM PDT I am able to read and write documents to database but I am experiencing some very strange behavior. If search for the name "jack" I get every document and Mike I get just one document but they're two. search method func findByFirstName(name string) { fmt.Println("looking for - ", name) client, ctx, _ := getConnection() quickstart := client.Database("ginPlay") namesCollection := quickstart.Collection("names") var p []person nameObject, err := namesCollection.Find(ctx, bson.M {"lastName": bson.D { {"$gt", name}, }}) if err = nameObject.All(ctx, &p); err != nil { panic(err) } for i := 0; i < len(p); i++ { fmt.Println(p[i]) } } output looking for - Jack Connected to MongoDB! {ObjectID("613b706bf47bc212c3928870") Mike Smith 25 Netflix} {ObjectID("613b706cf47bc212c3928872") Jack Jill 36 Surfing} {ObjectID("613b706ef47bc212c3928874") Jack Jill 25 Hiking} {ObjectID("613b706ff47bc212c3928876") Jack Jill 30 Snowboarding} looking for - Mike Connected to MongoDB! {ObjectID("613b706bf47bc212c3928870") Mike Smith 25 Netflix} this is what is in the database r.GET("/addPerson", func(c *gin.Context) { c.String(http.StatusOK, "Hello World!") p1 := person{Name: "Mike", LastName: "Foo", Age: 36, Hobbies: "Development"} p2 := person{Name: "Mike", LastName: "Smith", Age: 25, Hobbies: "Netflix"} p3 := person{Name: "Jack", LastName: "Jill", Age: 36, Hobbies: "Surfing"} p4 := person{Name: "Jack", LastName: "Jill", Age: 25, Hobbies: "Hiking"} p5 := person{Name: "Jack", LastName: "Jill", Age: 30, Hobbies: "Snowboarding"} writePerson(p1) writePerson(p2) writePerson(p3) writePerson(p4) writePerson(p5) }) database connection // GetConnection - Retrieves a client to the DocumentDB func getConnection() (*mongo.Client, context.Context, context.CancelFunc) { username := "foo" password := "pass" clusterEndpoint := "cluster0.ml6z7m.mongodb.net/db?retryWrites=true&w=majority" connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint) client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI)) if err != nil { log.Printf("Failed to create client: %v", err) } ctx, cancel := context.WithTimeout(context.Background(), connectTimeout * time.Second) err = client.Connect(ctx) if err != nil { log.Printf("Failed to connect to cluster: %v", err) } // Force a connection to verify our connection string err = client.Ping(ctx, nil) if err != nil { log.Printf("Failed to ping cluster: %v", err) } fmt.Println("Connected to MongoDB!") return client, ctx, cancel } controller r.GET("/mike", func(c *gin.Context) { c.String(http.StatusOK, "Mike") findByFirstName("Mike") }) r.GET("/jack", func(c *gin.Context) { c.String(http.StatusOK, "Jack") findByFirstName("Jack") }) |
Selenium 4 + geckodriver: printing webpage to PDF with custom page size Posted: 10 Sep 2021 07:59 AM PDT With Selenium 4 and chromedriver, I succeeded printing websites to PDF with custom page sizes (see Python code below). I would like to know the equivalent to do this with geckodriver/firefox. def send_devtools(driver, cmd, params={}): resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id url = driver.command_executor._url + resource body = json.dumps({'cmd': cmd, 'params': params}) response = driver.command_executor._request('POST', url, body) if (response.get('value') is not None): return response.get('value') else: return None def save_as_pdf(driver, path, options={}): result = send_devtools(driver, "Page.printToPDF", options) if (result is not None): with open(path, 'wb') as file: file.write(base64.b64decode(result['data'])) return True else: return False options = webdriver.ChromeOptions() # headless setting is mandatory, otherwise saving tp pdf won't work options.add_argument("--headless") driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=options) # chrome has to operate in headless mode to procuce PDF driver.get(r'https://example.my') send_devtools(driver, "Emulation.setEmulatedMedia", {'media': 'screen'}) pdf_options = { 'paperHeight': 92, 'paperWidth': 8, 'printBackground': True } save_as_pdf(driver, 'myfilename.pdf', pdf_options) |
How do I mark a radio button as "checked" within my Blazor app, while creating the radio buttons inside of a foreach loop? Posted: 10 Sep 2021 07:59 AM PDT I am populating a group of radio buttons in my Blazor app with a foreach loop: Dictionary<string,string> my_radio_options = new Dictionary<string,string>(){ {"optionone","Option One"} {"optiontwo","Option Two"} {"optionthree","Option Three"} {"optionfour","Option Four"} {"optionfive","Option Five"} } @foreach (KeyValuePair<String, String> entry in my_radio_options) { <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key"> } @code { private string my_selection; private void do_something() { // Use "my_selection" here ... } } I tried this: <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key" checked="@(entry.Key.Equals(my_radio_options.ElementAt(1).Key) ? "checked" : "")"> And this: @{bool first = true;} @foreach (KeyValuePair<String, String> entry in my_radio_options) { <input type="radio" name="my_selected_option" id="my_selected_option-@entry.Value" @onclick="() => my_selection = entry.Key" checked="@(first ? "checked" : "")"> @(first = false) } However, neither one of those works. How can I do this? |
How to decrypt and get real email adress Posted: 10 Sep 2021 07:59 AM PDT I'm just coming here with one question. It is possible to decrypt an email that looks like this: j7vb2jpqyqcx0rm+A08300342WSIT7PJPFBZS@marketplace.amazon.de I tried with spamguard but I can't get the correct email at all. I just want a suggestion, what could I use to get the right email. Thanks |
Gnome control center does not open Posted: 10 Sep 2021 07:59 AM PDT When I try to open Gnome control center it doesn't open. When I try to open it with the terminal it gives me this error: gnome-control-center: error while loading shared libraries: libnsl.so.2: cannot open shared object file: No such file or directory Everything happened as soon as I finished updating Arch |
Giving Error while python writes in excel file Posted: 10 Sep 2021 07:59 AM PDT I have am using python code to write the data into excel Template but the workbook gives an error while opening after the code runs and doesnot paste the data to template, Removed Part: /xl/pivotCache/pivotCacheDefinition1.xml part with XML error. (PivotTable cache) Load error. Line 1, column 0. Removed Feature: PivotTable report from /xl/pivotTables/pivotTable1.xml part (PivotTable view) Below code works fine in a simple file and not the template file def fill_sheet(self, wb,External_TM): for i in range(0 , len(self.Tabs_list)): sheet_name =self.Tabs_list[i] ws = wb[sheet_name] for colm in range(1,ws.max_column): if ws.cell(row = 4,column=colm).value ==self.months: c_idx=colm break r_idx=6 if i==0: data = Internal.values elif i==1: data = External_Others.values elif i==2: data=External_TM.values max_row, max_col = data.shape for r in range(max_row): if i==0: c_idx=colm+9 else: c_idx=colm+1 for c in range(1, max_col): if(data[r][c]!='NA'): ws.cell(row=r_idx, column=c_idx).value=data[r][c] c_idx=c_idx+1 r_idx=r_idx+1 return wb External_TM = Data.loc[(Data[self.divisions[1]]==self.divisions[0]) & (Data['RTB/CTB/ADC']==RTB_CTB_ADC)& (Data['Worker Category']=='Externals T&M'),['Updated City','External Category','FTE']] External_TM_category =pd.pivot_table(External_TM , index="Updated City", columns="External Category", values="FTE", aggfunc=np.sum) External_TM_category =External_TM_category.reindex(['A','B','C'], axis=1) `` The excel file has power query connections. Can that be the reason to show error. How do I fix it |
Limiting upload file size, maximum uploads in one request, and file type within the PHP script file itself Posted: 10 Sep 2021 08:00 AM PDT I've been dealing with a small problem that requires me to individually define maximum upload file size, limit maximum uploads in one POST and file types on a per-script basis. This means that I can't use the .htaccess file or php.ini to define max_post_size and other parameters that limit what can be uploaded. The script is just used to upload and store images on a publicly viewable webserver. The upload script works in tandem with ShareX. I eventually want to give access to hosting to a few others, so I want to limit the types that they can upload, how much they can upload in one request, the file size of their images. How would I add these parameters to the script itself instead of using server configurations to limit everyone? Here is the script: <?php $secret_key = "REDACTED"; //32-char $sharexdir = "REDACTED"; $domain_url = "REDACTED"; $lengthofstring = 7; $space= "\x20"; $linkembedu2800 =; function RandomString($length) { $keys = array_merge(range(0,9), range('a', 'z')); $key = ''; for($i=0; $i < $length; $i++) { $key .= $keys[mt_rand(0, count($keys) - 1)]; } return $key; } if(isset($_POST['secret'])) { if($_POST['secret'] == $secret_key) { $filename = RandomString($lengthofstring); $target_file = $_FILES["sharex"]["name"]; $fileType = pathinfo($target_file, PATHINFO_EXTENSION); if (move_uploaded_file($_FILES["sharex"]["tmp_name"], $sharexdir.$filename.'.'.$fileType)) { echo $domain_url.$sharexdir.$filename.'.'.$fileType.$space.$linkembedu2800; } else { echo 'ERROR: INTERNAL SERVER ERROR'; } } else { echo 'ERROR: INVALID SECRET KEY'; } } else { echo 'ERROR: NO POST DATA RECIEVED'; } ?> Thanks in advance. |
VS IDE can build, but run "dotnet build" command then got ".NETFramework,Version=v5.0 were not found" Posted: 10 Sep 2021 08:00 AM PDT My visual studio pro 2019 is v16.11.2. I can build my mvc project without any issue by pressing build button, and run this project very well. Of cause, I've installed .net sdk 5.0.400 on my win10 enter image description here Currently I'm studying docker, so I need to run command to build my project. dotnet build "MVConDocker.csproj" -c Release -o /app/build unfortunately it failed. error MSB3971: The reference assemblies for ".NETFramework,Version=v5.0" were not found. enter image description here |
How to split a string based on a combination of characters? Posted: 10 Sep 2021 08:00 AM PDT I have a string (path) that looks like this: list_string = ["\path\to\file1.json\path\to\file2.json\path\to\file3.json"] How can I split this string into the correct list of paths ? Current code: for line in list_string: line.split('\p') Desired output: list_string = ["\path\to\file1.json", "\path\to\file2.json", "\path\to\file3.json"] |
Trigger one Kafka consumer by using values of another consumer In Spring Kafka Posted: 10 Sep 2021 07:59 AM PDT I have one scheduler which produces one event. My consumer consumes this event. The payload of this event is a json with below fields: private String topic; private String partition; private String filterKey; private long CustId; Now I need to trigger one more consumer which will take all this information which I get a response from first consumer. @KafkaListener(topics = "<**topic-name-from-first-consumer-response**>", groupId = "group" containerFactory = "kafkaListenerFactory") public void consumeJson(List<User> data, Acknowledgment acknowledgment, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) List<Integer> partitions, @Header(KafkaHeaders.OFFSET) List<Long> offsets) { // consumer code goes here...} I need to create some dynamic variable which I can pass in place of topic name. similarly, I am using the filtering in the configuration file and I need to pass key dynamically in the configuration. factory.setRecordFilterStrategy(new RecordFilterStrategy<String, Object>() { @Override public boolean filter(ConsumerRecord<String, Object> consumerRecord) { if(consumerRecord.key().equals("**Key will go here**")) { return false; } else { return true; } } }); How can we dynamically inject these values from the response of first consumer and trigger the second consumer. Both the consumers are in same application |
How to access Amazon S3 data via AWS CloudFront in r? Posted: 10 Sep 2021 07:59 AM PDT I built an r shiny web app in rStudio that pulls data from an Amazon S3 bucket using the access key, secret access key and region via EC2 in Sys.setenv() but would like to utilize AWS CloudFront. I already set up a CloudFront distribution via the AWS online console for the Amazon S3 bucket in question but do not quite understand how to actually assure data is pulled via CloudFront rather than EC2. I could also be misunderstanding the relationship between Amazon S3 and EC2/CloudFront, thus any information is much appreciated. |
For Loop with If Conditions to Return Non-NA Values Posted: 10 Sep 2021 07:59 AM PDT I am trying to do a simple for loop with if statements to get non-NA values, however, receiving an error. Could you help? df = pd.DataFrame({'Platform ID' : [1,2,3,4], "Delivery Date" : [str(2009), float("nan"), float("nan"), float("nan")], "Build Year" : [float("nan"),str(2009),float("nan"), float("nan")], "In Service Date" : [float("nan"),float("nan"), str("14-11-2009"), float("nan")]}) df.dtypes df def delivery_year(delivery_year, build_year, service_year): out = [] for i in range(0,len(delivery_year)): if any(delivery_year.notna()): out[i].append(delivery_year) if any(delivery_year[i].isna() and build_year[i].notna()): out[i].append(build_year) elif any(build_year[i].isna()): out[i].append(service_year.str.strip().str[-4:]) else: out[i].append(float("nan")) return out df["Delivery Year"] = delivery_year(df["Delivery Date"], df["Build Year"], df["In Service Date"]) Error Message: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). |
Install Offline Windows Updates(.msu) to remote servers Posted: 10 Sep 2021 07:59 AM PDT I'm trying to get a script together to remotely install some windows updates on some remote servers that are connected in an offline domain. I have tried regular PS Remoting and after some research, I think what I am trying to do isnt supported by microsoft. When checking my event logs I have a bunch of these errors. Edit I wanted to add that I have tried running the .\Install2012R2.ps1 script from my local computer, modified to have the Invoke-Command in that and have it run the update portion of the original Install2012R2.ps1 and I would get the same errors. I was hoping that by placing the script on each server that it would like that more. End Edit Windows update could not be installed because of error 2147942405 "Access is denied." (Command line: ""C:\Windows\System32\wusa.exe" "C:\Updates\windows8.1-kb4556853-x64.msu" /quiet /norestart") I have tried running Invoke-Command as credentialed to an administrator account on the servers but I have been having no luck and was looking for some advice if someone has maybe tried/done this before. $Servers = @("V101-Test1","V101-Test2") $Username = 'admin' $Password = 'Password'#not actual password $pass = ConvertTo-SecureString -AsPlainText $Password -Force $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass Get-PSSession | Remove-PSSession New-PSSession -ComputerName $Servers foreach($Server in $Servers){ Get-ChildItem -Path C:\Source\Temp -Recurse | Copy-Item -Destination "\\$Server\c$\Updates\" -Force } Invoke-Command $Servers -Credential $Cred -ScriptBlock{ & "C:\Updates\Install2012R2.ps1" } EDIT 2 Here is the actual install code of the Install2012R2.ps1 script $updatedir = ".\" $files = Get-ChildItem $updatedir -Recurse $msus = $files | ? {$_.extension -eq ".msu"} $exes = $files | ? {$_.extension -eq ".exe"} foreach ($file in $msus){ $KBCtr++ $fullname = $file.fullname # Need to wrap in quotes as folder path may contain space $fullname = "`"" + $fullname + "`"" $KBN = $fullname.split('-')[1] # Need to wrap in quotes as folder path may contain space $fullname = "`"" + $fullname + "`"" # Specify the command line parameters for wusa.exe $parameters = $fullname + " /quiet /norestart" # Start services and pass in the parameters $install = [System.Diagnostics.Process]::Start( "wusa",$parameters ) $install.WaitForExit() } |
typeahead.js with multiselect extension: how do I set a default selection? Posted: 10 Sep 2021 07:59 AM PDT I have an app with jQuery typeahead and the typeahead multiselect extension. On load I would like certain elements to be selected by default, how do I do that? $(document).ready(function() { waitingDialog.hide(); $("#typeahead").typeaheadmulti({ minLength: 1, hint: false, highlight: true, autocomplete: false, }, { name: 'Typeahead', source: function(query, syncResults, process) { var args = {}; args.Str = query; gers = aj("Search", function(res) { names = []; ids = {}; res.d = JSON.parse(res.d); $.each(res.d, function(i, lkp) { names.push(lkp.name.trim().toUpperCase()); }); process(names); }, JSON.stringify(args), null); }, limit: 10 }) }); |
how to initialize string[20] in the constructor? Posted: 10 Sep 2021 07:59 AM PDT in this question , im required to have a string of limit 20 for owner and address. but I'm unable to initialize these two strings in the constructer, hence in the main code, I get an error no default constructor for class House what should i do to avoid this error? class House { private: string owner[20]; string address[20]; int bedrooms; float price; public: House(string owner[20], string address[20], int bedrooms = 0, float price = 0.0) { this->owner[20] = owner[20]; this->address[20] = address[20]; this->bedrooms = bedrooms; this->price = price; } void setOwner(string owner[20]) { this->owner[20] = owner[20]; } void setAddress(string address[20]) { this->address[20] = address[20]; } void setBedrooms(int bedrooms) { this->bedrooms = bedrooms; } void setPrice(float price) { this->price = price; } string getOwner() { return owner[20]; } string getAddress() { return address[20]; } int getBedrooms() { return bedrooms; } float getPrice() { return price; } }; int main() { House* h[100]; House houseinfo; h->houseinfo; return 0; } |
Where is header and payload information about a calloc stored in heap? Posted: 10 Sep 2021 07:59 AM PDT I want to know how this structure & calloc are allocated in heap. I mean how glibc keep information in memory like this is structure this is its data type so on. #include<stdio.h> struct student{ int rollno; char level; }; int main(){ struct student *p = calloc(1,sizeof(struct student)); p->rollno=767; p->level='A'; printf("addr of p is =%p\n",p); printf("student_struct_size=%ld\n",sizeof( } In my system addr of p is =0x555555756260 (gdb) x/16b 0x555555756260 0x555555756260: -1 2 0 0 65 0 0 0 0x555555756268: 0 0 0 0 0 0 0 0 I can understand why 65 is coming but where is 767, also where is header information about calloc (what is boundary of calloc) If i Do x/16b 0x555555756260-8 i get 33 , is 33 is size of all payload + header information , can u justify why 33 is coming (gdb) x/16b 0x555555756260-8 0x555555756258: 33 0 0 0 0 0 0 0 0x555555756260: -1 2 0 0 65 0 0 0 |
How to use TypeScript's indexed access types with nullable types? Posted: 10 Sep 2021 07:59 AM PDT I'm trying to define a TypeScript type in terms of another type. This works: type Result = { data: { nestedData: { foo: string; bar: string } } }; type NestedData = Result['data']['nestedData']; But, when the data property is nullable, this doesn't work: type Result = { data: { nestedData: { foo: string; bar: string } } | null }; type NestedData = Result['data']['nestedData']; and results in the error: Property 'nestedData' does not exist on type '{ nestedData: { foo: string; bar: string; }; } | null'.(2339) How can I define my NestedData type in terms of Result , without duplicating any part of Result 's typings? Demo on TypeScript Playground Edit: I'm getting my NestedData type from a codegen tool and I'm defining NestedData as a shorter type alias. In reality the typing is longer so I want to minimize repetition. |
How to expand preprocessor variable inside a macro? Posted: 10 Sep 2021 07:59 AM PDT In the header file I have declared a preprocessor variable and I want to create a macro that concatenate it to the name of a function to generate the final function name: #define CLASS_NAME_ONE my_package_name_MyClassName #define FUNCTION_NAME_OF(className, functionName) Java_ ## _ ## className ## _ ## functionName #define FUNCTION_NAME_OF_CLASS_NAME_ONE(functionName) FUNCTION_NAME_OF(CLASS_NAME_ONE, functionName) ... And I use it in the implementation file as follow: jobject FUNCTION_NAME_OF_CLASS_NAME_ONE(functionName)(JNIEnv* jNIEnv, jobject instance, jclass instanceType) ... But the generated code is: jobject Java_CLASS_NAME_ONE_functionName(JNIEnv* jNIEnv, jobject instance, jclass instanceType) ... How can I solve? |
undefined reference to `stack_init' Posted: 10 Sep 2021 08:00 AM PDT test.c #include <stdio.h> #include <stdlib.h> #include "dslib.h" //#include "stack.c" int main() { stack myStack; char buffer[1024]; stack_init(&myStack, 6); int i; for(i = 0; i < myStack.max; i++){ stack_push(&myStack, (i+1)*2); } printf("Hello\n"); return 0; stack.c #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "dslib.h" //#define stack_init main void stack_init(stack *s, int capacity) { // struct stack_t *s = (struct stack_t*)malloc(sizeof(struct stack_t)); s->max = capacity; s->count = -1; s->data = (int*)malloc(capacity * sizeof(int)); //return s; } int stack_size(stack *s) { return s->count; } int stack_pop(stack *s) { if(s->count == 0){ return -1; } s->count--; int pop = s->data[s->count]; s->data[s->count] = 0; return pop; } void stack_push(stack *s, int e) { if(s->count != s->max){ s->data[s->count] = e; s->count++; } } void stack_deallocate(stack *s) { free(s->data); } dslib.h #ifndef DSLIB_H #define DSLIB_H #include <stdio.h> #include <stdlib.h> typedef struct stack { int count; // the number of integer values currently stored in the stack int *data; // this pointer will be initialized inside stack_init(). Also, the actual size of //the allocated memory will be determined by "capacity' value that is given as one of the //parameters to stack_init() int max; // the total number of integer values that can be stored in this stack }stack; void stack_init(stack* s, int capacity); int stack_size(stack *s); int stack_pop(stack *s); void stack_push(stack *s, int e); void stack_deallocate(stack *s);
|
No comments:
Post a Comment