text:
Q: JSP use contents of an array list in a drop down box I have an arraylist that is declared and populated in a JSP file:
<% for(int i=0; i< GDI.getRow(); i++){
    associatedLines[i] = GDI.getRow().get(i).getNumplanindex;
}

ArrayList<Integer> availableLines = new ArrayList<Integer>();
for(int i=0; i<associatedLines.length; i++){
    if(associatedLines[i] == null){
         availableLines.add(i);
    }
}

%>

I would like to use the contents of availableLines in the dropdown list and be able to store the value selected to be used somewhere else.
I am almost certain that I need to use JSTL but I am not sure how to do it.
Hopefully somebody can help. Thanks!

A: You can add the bellow line just after the for loop in your scriptlet:
request.setAttribute("availableLines", availableLines);

And then you can use the availableLines variable in your drop down list using JSTL like bellow:
 <select>
    <c:forEach var="line" items="${availableLines}">
        <option><c:out value="${line}"/></option>
    </c:forEach>
 </select>

I think, this answers your original question.
Edit:
But one thing you should know that, writing scriptlet is deprecated for years! So it is advised to move your scriptlet code to your corresponding servlet. Here is a step by step tutorial for Servlet and jsp  for beginners.


text:
Q: How to remove the floating number ending in python? A beginner python programming learner here.
I'm making a very simple two number calculator in python. Although it runs perfectly, I can't fix the issue with floating numbers ending with ".0". I want to remove this ending. I tried a few things but they didn't work. What condition do I need to add inside the code? Could you please take a look at it below:
    def calculator():
        num1 = float(input('First number: '))
        operator = input('+, -, / or * ? ')
        num2 = float(input('Second Number: '))

        if operator == '+':
            return print(num1, '+', num2, '=', num1 + num2)
        elif operator == '-':
            return print(num1, '-', num2, '=', num1 - num2)
        elif operator == '/':
            return print(num1, '/', num2, '=', num1 / num2)
        elif operator == '*':
            return print(num1, '*', num2, '=', num1 * num2)

calculator()

Thank you in advance!
I exactly did what @water-winter suggested but whenever I execute the program and enter numbers and operator I get this error: if result.is_integer():
AttributeError: 'int' object has no attribute 'is_integer'
Update: Looks like that only "/" operator works perfectly. The other 3 operators give the same error above. :/
New Update: Finally I managed to make the calculator programming flawlessly!
def calculator():
    num1 = float(input("First number: "))
    operator = input("Choose: +, -, /, or *")
    num2 = float(input("Second number: "))
    num1 = int(num1) if num1.is_integer() else num1
    num2 = int(num2) if num2.is_integer() else num2
    add = (num1 + num2)
    subtract = (num1 - num2)
    divide = (num1 / num2)
    multiply = (num1 * num2)

    if operator == "+" and add % 1 == 0:
        print(num1, "+", num2, "is equal to:", int(add))
    elif operator == "+" and not add % 1 == 0:
        print(num1, "+", num2, "is equal to:", add)
    elif operator == "-" and subtract % 1 == 0:
        print(num1, "-", num2, "is equal to:", int(subtract))
    elif operator == "-" and not subtract % 1 == 0:
        print(num1, "-", num2, "is equal to:", subtract)
    elif operator == "/" and divide % 1 == 0:
        print(num1, "/", num2, "is equal to:", int(divide))
    elif operator == "/" and not divide % 1 == 0:
        print(num1, "/", num2, "is equal to:", divide)
    elif operator == "*" and multiply % 1 == 0:
        print(num1, "*", num2, "is equal to:", int(multiply))
    elif operator == "*" and not multiply % 1 == 0:
        print(num1, "*", num2, "is equal to:", multiply)

calculator()

Thank you guys, for the help and suggestions. They helped a lot! :)

A: First, there's a built-in function for float to check for integer and there's int() to trip off decimal places.
>> float(0.5).is_integer()
>> False
>> float(3.0).is_integer()
>> True
>> int(float(5.5))
>> 5
>> int(float(3))
>> 3

Second, if you simply want to print, the return keyword is unnecessary.
def calculator():
    num1 = float(input('First number: '))
    operator = input('+, -, / or * ? ')
    num2 = float(input('Second Number: '))

    num1 = int(num1) if num1.is_integer() else num1
    # This line is equivalent to:
    # if num1.is_integer():
    #     num1 = int(num1)
    # else:
    #     num1 = num1

    num2 = int(num2) if num2.is_integer() else num2

    if operator == '+':
        result = num1 + num2
        result = int(result) if result.is_integer() else result
        print(num1, '+', num2, '=', result)
    elif operator == '-':
        ...
calculator()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom php code error for Woocommerce Elementor Template with ACF I get an 500 error for the Product template I pasted the shortcode.
I created a Shortcode for displaying an video if user has bought the specific product.
The Video URL is from an ACF field.
// Shortcode for Video from ACF
function wpc_elementor_shortcode( $atts ) {
    global $product;
    if ( ! is_user_logged_in() ) return;
    if ( wc_customer_bought_product( '', get_current_user_id(), $product->get_id() ) ) {
    echo get_field('video_tutorial');
    }
}
add_shortcode( 'purchase_video_tutorial', 'wpc_elementor_shortcode');

On Front-End it works but within the elementor builder it shows 500 error if shortcode [purchase_video*_*tutorial] is placed.
Debugging showing error for code above:
Uncaught Error: Call to a member function get_id() on null in ..... functions.php:133

What do I need to add to the php code to fix this error for elementor pagebuilder?

A: Validation means checking that object you are accessing isn't null, like this:
if ( $product != null && wc_customer_bought_product( '', get_current_user_id(), $product->get_id() ) ) {

Also, the shortcode should return the string, not print it
echo get_field('video_tutorial');

to
return get_field('video_tutorial');

Also, wc_customer_bought_product, first parameter is customer's email
    $current_user = wp_get_current_user();
    $customer_email = $current_user->email;
    wc_customer_bought_product($customer_email, get_current_user_id(), $product->get_id() )


text:
Q: How do I add new elements to XML using PHP DOM deeper than the root? All of the examples I can find online about this involve simply adding content to an XML file at the document root, but I really need to do it deeper than that.
My XML file is simple, I have:
<?xml v1 etc>
<channel>
<screenshots>
<item>
  <title>Image Title</title>
  <link>www.link.com/image.jpg</link>
</item>
</screenshots>
</channel>

All I want to be able to do is add new "item" elements, each with a title and link. I know I need to be using PHP DOM, but I'm stumped as to how to code it so that it adds data within "screenshots" rather than overwriting the whole document. I have a suspicion I may need to use XPath too, but I have no idea how!
The code I have pieced together from online examples looks like this (but I'm certain it's wrong)
$newshottitle = "My new screenshot";
$newshotlink = "http://www.image.com/image.jpg";

$dom = newDomDocument;
$dom->formatOutput = true;
$dom->load("../xml/screenshots.xml");

$dom->getElementsByTagName("screenshots");
$t = $dom->createElement("item");
$t = $dom->createElement("title");
$t->appendChild($dom->createTextNode("$newshottitle"));

$l = $dom->createElement("link");
$l->appendChild($dom->createTextNode("$newshotlink"));

$dom->save("../xml/screenshots.xml");

A:
adding content to an XML file at the document root, but I really need to do it deeper than that.

You're not adding content anywhere at the moment! You create <title> and <link> element nodes with text in, then you do nothing with them. You should be passing them into 'appendChild' on the <item> element node (which also you are currently creating and immediately throwing away by not assigning it to a variable).
Here's a starting-point:
$screenshots= $dom->getElementsByTagName("screenshots")[0];

$title= $dom->createElement("title");
$title->appendChild($dom->createTextNode($newshottitle));
$item= $dom->createElement("item");
$item->appendChild($title);
$screenshots->appendChild($item);


text:
Q: Download the file from either of two machines using SCP? I have a below bash shell script which I am running from machineA and that shell script will try to download a tar file from either of these two machines machineB and machineC and put it in /testing/directory1 in machineA.
And both of the machines (machineB and machineC) will have same file test.tar in the same directory /data/v1.
I need to download test.tar file from either of those two machines(machineB and machineC) from /data/v1 directory. If machineB is up, then I will download the tar file from machineB and if it is down, then I will download the same tar file from machineC..
But currently in my bash shell script suppose for whatever reason if machineB is down, then I guess it won't even try to download the same tar file from machineC and it will throw an exception and stop the shell script.
I want to use set -e but it should throw an exception only when both of the machines are down and not able to download the tar file from machineB and machineC. If machineB is down for whatever reason, then it should try downloading from machineC..
#!/bin/bash
set -e

readonly PATH_LOCATION=/testing/directory1
readonly MACHINES=(machineB machineC)
readonly FILE_LOCATION=/data/v1
readonly FILE_NAME=test.tar

length1=$(ssh -o "StrictHostKeyChecking no" david@${MACHINES[0]} "ls '$FILE_LOCATION' | wc -l")
length2=$(ssh -o "StrictHostKeyChecking no" david@${MACHINES[1]} "ls '$FILE_LOCATION' | wc -l")

echo $length1
echo $length2

if [ "$length1" -gt 0 ] || [ "$length2" -gt 0 ]
then
    rm -rf $PATH_LOCATION/*
    scp david@${MACHINES[0]}:$FILE_LOCATION/$FILE_NAME $PATH_LOCATION/. || scp david@${MACHINES[1]}:$FILE_LOCATION/$FILE_NAME $PATH_LOCATION/.
    tar -xvf $PATH_LOCATION/$FILE_NAME -C $PATH_LOCATION
    rm $PATH_LOCATION/$FILE_NAME
fi

Any thoughts how this can be done? I want to use scp only here not rsync as I need to spend some time understanding rsync.

A: You are needlessly complicating things. Just try machineA and if that fails, go to machineB:
#!/usr/bin/env bash
set -e

readonly PATH_LOCATION=/testing/directory1
readonly MACHINES=(machineB machineC)
readonly FILE_LOCATION=/data/v1
readonly FILE_NAME=test.tar
readonly TARGET="$FILE_LOCATION/$FILE_NAME"

for MACHINE in ${MACHINES[@]}; do
    scp david@$MACHINE:$TARGET $PATH_LOCATION && break
done

If you want to know which host you downloaded from, you could do:
for MACHINE in ${MACHINES[@]}; do
    if scp david@$MACHINE:$TARGET $PATH_LOCATION; then
      echo "Downloaded from $MACHINE";
      break;
    fi
done

And if you want to do something else if neither machine is up:
for MACHINE in ${MACHINES[@]}; do
    if scp david@$MACHINE:$TARGET $PATH_LOCATION; then
      echo "Downloaded from $MACHINE";
      break;
    fi
done
if [[ $? -eq 1 ]]; then
   echo "Download failed"
fi

A: if ping -c 3 -W 1 hostA >/dev/null; then
 SRV=hostA
elif ping -c 3 -W1 hostB >/dev/null; then
 SRV=hostB
else
 echo "cannot contact either hostA or hostB"
 exit 1
fi

scp david@$SRV:$FILE_LOCATION/$FILE_NAME $PATH_LOCATION/.
RET=$?

echo "Return code is $RET"

...


text:
Q: A Stackoverflow mapping (Hibernate) Suppose a mapping like this one
@Entity
public class User {

    private Integer id

    private List<Info> infoList;

    @Id
    public getId() {
        return this.id;
    }

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="USER_ID", insertable=false, updateable=false, nullable=false)
    public getInfoList() {
        return this.infoList;
    }

    public void addQuestion(Info question) {
        info.setInfoCategory(InfoCategory.QUESTION);
        info.setInfoId(new InfoId(getId(), getInfoList().size()));

        getInfoList().add(question);
    }

    public void addAnswer(InfoRepository repository, Integer questionIndex, Info answer) {
        Info question = repository.getInfoById(new InfoId(getId(), questionIndex));

        if(question.getInfoCategory().equals(InfoCategory.ANSWER))
            throw new RuntimeException("Is not a question");

        if(question.getAnswer() != null)
            throw new RuntimeException("You can not post a new answer");

        answer.setInfoCategory(InfoCategory.ANSWER);
        answer.setInfoId(new InfoId(getId(), getInfoList().size()));

        getInfoList().add(answer);

        question.setAnswer(answer);
    }

}

And a question and answer mapped by a Info class
@Entity
public class Info implements Serializable {

    private InfoId infoId;

    private Info answer;

    private InfoCategory infoCategory;

    public Info() {}

    @Embeddable
    public static class InfoId {

        private Integer userId;
        private Integer index;

        public InfoId(Integer userId, Integer index) {
            this.userId = userId;
            this.index = index;
        }

        @Column("USER_ID", updateable=false, nullable=false)
        public getUserId() {
            return this.userId;
        }

        @Column("INFO_INDEX", updateable=false, nullable=false)
        public getIndex() {
            return this.index;
        }

        // equals and hashcode

    }

    // mapped as a ManyToOne instead of @OneToOne
    @ManyToOne
    JoinColumns({
        JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updateable=false),
        JoinColumn(name="ANSWER_INDEX", referencedColumnName="INFO_INDEX", insertable=false)
    })
    public Info getAnswer() {
        return this.answer;
    }

    @EmbeddedId
    public InfoId getInfoId() {
        return this.infoId;
    }

}

In getAnswer i use ManyToOne instead of OneToOne because some issues related to OneToOne mapping. A OneToOne can be mapped as a ManyToOne (unique=true in @JoinColumn). INFO_INDEX is not related to any specific purpose. Just a key in order to supports a compound primary key in a LEGACY system.
Before answering, take care of the following:

If an object has an assigned identifier, or a composite key, the identifier SHOULD BE ASSIGNED to the object instance BEFORE calling save()

So i have to map JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updateable=false) in getAnswer because Hibernate does not allow two mutable properties share the same collumn (userId also uses USER_ID) otherwise i will get USER_ID in answer property must be mapped with insertable=false, updateable=false
Now take a look at getAnswer mapping
@ManyToOne
JoinColumns({
    JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updateable=false),
    JoinColumn(name="ANSWER_INDEX", referencedColumnName="INFO_INDEX", insertable=false)
})

Because it, Hibernate complains you can not mix different insertable and updatable
What should i do in order to pass it ?
Take care it is a LEGACY system.
regards,

A: You would drastically simplify your mapping by forgoing embedded id and using a surrogate PK instead.
If you need to use InfoId.index for some purpose (to order questions / answers? you can specify that in list mapping), keep it as a regular property.
UserId will be replaced by ManyToOne on User; the other association end (in User class) will be mapped as @OneToMany(mappedBy="User")
Why is answer mapped as ManyToOne? Shouldn't it be OneToMany (e.g. 1 question to many answers)? Either way, mapping class onto itself is less than ideal - you're basically implementing an "adjacency list" model hierarchy which is inefficient; plus in your case you'll need to make sure that it's no more than 2 levels. I'd map Question and Answer as separate classes; you can have them implement a common interface or extend the same base (possibly abstract) class; either way you'll be able to enjoy implicit polymorphism provided by Hibernate.

A: According to question in getAnswer mapping
@ManyToOne
JoinColumns({
    JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updateable=false),
    JoinColumn(name="ANSWER_INDEX", referencedColumnName="INFO_INDEX", insertable=false)
})

Hibernate will complain because it does not allows mix different insertable and updatable. Notice a insertable and updateable in USER_ID JoinColumn and only insertable in ANSWER_INDEX JoinColumn.
So in order to pass it, i set up ANSWER_INDEX JoinCollumn accortding to
JoinColumn(name="ANSWER_INDEX", referencedColumnName="INFO_INDEX", insertable=false, updateable=false)

This way, Hibernate will not complain.
And i set up a new property called answerIndex
private Integer answerIndex;

@Column(name="ANSWER_INDEX", insertable=false)
public void getAnswerIndex() {
    return this.answerIndex;
}

Then in User addAnswer
public void addAnswer(InfoRepository repository, Integer questionIndex, Info answer) {
    Info question = repository.getInfoById(new InfoId(getId(), questionIndex));

    if(question.getInfoCategory().equals(InfoCategory.ANSWER))
        throw new RuntimeException("Is not a question");

    if(question.getAnswer() != null)
        throw new RuntimeException("You can not post a new answer");

    answer.setInfoCategory(InfoCategory.ANSWER);
    answer.setInfoId(new InfoId(getId(), getInfoList().size()));

    getInfoList().add(answer);

    // Added in order to set up AnswerIndex property
    question.setAnswerIndex(answer.getInfoId().getIndex());
}


text:
Q: Configuring webapp.runner to accept https and http traffic in dev environment I have a heroku project, and I am successfully using https in my production environment.  I am not sure how to configure webapp.runner (embedded tomcat) to accept connections on both http and https in my dev environment.  Is there a configuration for this?  Or should I grab the source files and edit the code?  Right now I am toggling all of the https domains to http in my dev environment, but that is not ideal, and I can't see if https functionality is working without deploying to heroku.

A: In the lack of other responses, I try to answer this but I am not a Heroku user.
I think it depends on how you install/launch webapp.runner .
Tomcat can be configured for this. Search for the file "server.xml" which contains Tomcat service definition. Look for the following piece:
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           URIEncoding="UTF-8"
           redirectPort="8443" />

In order to enable HTTPS, you need to change it following the guidelines at http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html .
However, note that under Heroku HTTPS  shall be handled by the balancer as per https://devcenter.heroku.com/articles/http-routing, and I think your application is actually accessed via HTTP . In other words, your application in Heroku would not receive HTTPS traffic.

A: You can't "manually" configure SSL on Heroku, you need to get Heroku's SSL Endpoint Add-On: https://addons.heroku.com/ssl
This article explains the installation process in detail, it's pretty easy to setup: https://devcenter.heroku.com/articles/ssl-endpoint

Updated to better answer poster's question
This is how to run your app locally using maven's jetty plugin:
Step 1: Add this to your pom.xml under your development profile:
   <plugin>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty-maven-plugin</artifactId>
      <version>8.1.4.v20120524</version>
      <configuration>
         <webAppConfig>
            <contextPath>/</contextPath>
         </webAppConfig>
         <connectors>
            <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
               <port>8080</port>
               <maxIdleTime>60000</maxIdleTime>
            </connector>
            <connector implementation="org.eclipse.jetty.server.ssl.SslSocketConnector">
               <port>8443</port>
               <maxIdleTime>60000</maxIdleTime>
               <keystore>${project.build.directory}/jetty-ssl.keystore</keystore>
               <password>jetty6</password>
               <keyPassword>jetty6</keyPassword>
            </connector>
         </connectors>
      </configuration>
   </plugin>
   <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>keytool-maven-plugin</artifactId>
      <executions>
         <execution>
            <phase>generate-resources</phase>
            <id>clean</id>
            <goals>
               <goal>clean</goal>
            </goals>
         </execution>
         <execution>
            <phase>generate-resources</phase>
            <id>genkey</id>
            <goals>
               <goal>genkey</goal>
            </goals>
         </execution>
      </executions>
      <configuration>
         <keystore>${project.build.directory}/jetty-ssl.keystore</keystore>
         <dname>cn=localhost</dname>
         <keypass>jetty6</keypass>
         <storepass>jetty6</storepass>
         <alias>jetty6</alias>
         <keyalg>RSA</keyalg>
      </configuration>
   </plugin>

Step 2: run the app
mvn clean jetty:run -Pdevelopment


text:
Q: TwitterSession must not be null I have used this code to compose tweet but getting TweitterSession error. Here, I attached log, please help me to resolved this issue.
//In Application Class
TwitterConfig config = new TwitterConfig.Builder(this)
                    .logger(new DefaultLogger(Log.DEBUG))//enable logging when app is in debug mode
                    .twitterAuthConfig(new TwitterAuthConfig("ConsumerKey", "ConsumerSecret"))//pass the created app Consumer KEY and Secret also called API Key and Secret
                    .debug(true)//enable debug mode
                    .build();

            //finally initialize twitter with created configs

            Twitter.initialize(config);

//OnClick on button
final TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
            final Intent intent = new ComposerActivity.Builder(MainActivity.this)
                    .session(session)
                    .text("Love where you work")
                    .hashtags("#twitter")
                    .createIntent();
            startActivity(intent);

Logs::
TwitterSession must not be null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5461)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.IllegalArgumentException: TwitterSession must not be null
        at com.twitter.sdk.android.tweetcomposer.ComposerActivity$Builder.session(ComposerActivity.java:95)
        at com.example.inextrix.twittereazydemo.MainActivity.onCreate(MainActivity.java:51)
        at android.app.Activity.performCreate(Activity.java:6251)


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) while my backend accepts the request Is it possible to use 2 patch on express ? cause I'm having trouble on my routes. my add product works perfectly. but the other one is giving me 404 status on client side. I tried to console my req.body and the data was accepted.. I'm kinda confused what's the problem in here.
here's my server side routes.
router.patch('/admin/collections/all/:id', addOwnerProducts);
router.patch('/admin/collections/view/:id', updateOwnerProduct);

I'm not sure if the problem was one client side or server side. I'm currently using axios for my request and here's the axios for my update product.
export const editItem = (admin,productname,price,quantity,categoryfilter,description,timestamp) => api.patch(`/admin/collections/view/${admin}`,
    {
        store: [
            {
                productname: productname,
                price: price,
                quantity: quantity,
                categoryfilter: categoryfilter,
                description: description,
                timestamp: timestamp
            }
        ]
    }
)

here's the error on the client side after the request.

A: You can have multiple endpoints using the same HTTP verb in a router. it will only match the first applicable route.
Not sure about what's going on. Let's do the trivial fist:

*

*Is your router being used by the app? app.use(router) Make sure these patch routes are being looked up.

*Is there any other route matching the endpoint?

*Is there an endpoint sending status 404 first? res.sendStatus(404)

*Isn't it any typo problem?

Hope this gives an insight


text:
Q: How to use Powershell method or any other batch method to modify a LOCAL group policy? SCCM is the method we deploy Windows updates to clients. We have a portion of computers that have a local group policy setting under:
Local Computer policy > Administrative Templates > Windows Components > Windows update
The setting is called "Specify intranet Microsoft update service location"
Basically the wuahandler.log is complaining of :
Enabling WUA Managed server policy to use server: http://servername.domain.local:8530
Group policy settings were overwritten by a higher authority (Domain Controller) to: Server https://servername.domain.local:8531 and Policy ENABLED
Failed to Add Update Source for WUAgent of type (2) and id ({C2F93D44-EAB3-4D5E-9330-7806157D92AD}). Error = 0x87d00692.
I can see that for whatever reason SCCM is not modifying the local group policy and its causing a conflict.
The pc's that have no issue have both the local group policy and policies under hklm > policies > windows update as the correct name (with port 8531).
I am basically asking how can i change the "specify intranet microsoft update service location ' using powershell or an automated method to remediate the 300 pc's that have a mismatched port number. modifying the HKLM keys under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate ive already taken care of. But this is not doing anything to resolve my issue.
any help would be appreciated.

A: There are many articles all over the web on using PowerShell and local policy management. Just search for them. Using a string like 'PowerShell manage local policy' and you will get a long list to consume.
There is even a module via the MS PowershellGallery.com for Local Policy Management.
Find-Module -Name 'PolicyFileEditor' |
Save-Module -Path "$env:USERPROFILE\Documents\WindowsPowerShell\Modules" -Force
Install-Module -Name 'PolicyFileEditor'

And blogged about its use is here:
How to manage Local Group Policy with Powershell
You can even just secedit.
Take a look at this Q&A
So, sure you can mess with Local Policy, be if your SCCM settings getting overridden by a higher authority, then any setting you'd do wit PowerShell would as well.

A: Please make sure that in case of SCCM/MECM or installations with system user (NT-Authority\System) you do not use -Scope CurrentUser, otherwise you will have the same problem as described here: https://github.com/PowerShell/PowerShellGetv2/issues/651
In a system context Install-Module does not create a Documents folder in the system profile if -Scope CurrentUser is used.
If you want to use -Scope CurrentUser anyway, you have to create the folder "C:\Windows\system32\config\systemprofile\Documents\PowerShell\Modules" or at least "C:\Windows\system32\config\systemprofile\Documents" first, so that the module is installed for the system user.


text:
Q: Link windows.h (WNDCLASSEX) code in VS2010 console application I have a VS2010 Win32 console application. Within this console application I try to attach a window as child to another Win32 app. But I do not get the application linked (it compiles, just the linker issue AFAIK):
Error   1   error LNK2019: unresolved external symbol "long __stdcall viewproc(struct HWND__ *,unsigned int,unsigned int,long)" (?viewproc@@YGJPAUHWND__@@IIJ@Z) referenced in function "void __cdecl createFSXWindow(void)" (?createFSXWindow@@YAXXZ)  H:\Projects\VisualStudioNet2010\FSXTests\Menu Items\Menu Items\MenuItems.obj    Menu Items

I have added all libs from a Win32 Windows project under Linker/include:
kernel32.lib;user32.lib;gdi32.lib;winspool.lib; comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib; odbccp32.lib;%(AdditionalDependencies)

Remark: Just to clarify, I do NOT(!) try to attach the window to the console window, but another Win32 application, so it is not about "Make a win32 console app display a window"
The issue comes in once I add the window code such as:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
....

// window
WNDCLASSEX wc;
wc.style = CS_HREDRAW | CS_VREDRAW ;
wc.lpfnWndProc = viewproc;

When I check the command line of the linker the only difference between my console app and an Win32 app is SUBSYSTEM:CONSOLE vs. SUBSYSTEM:WINDOWS
Any hints?

A: The linker error just tells you that you forgot to write the viewproc() function.
You declared it, the compiler is happy, but didn't implement it, the linker is unhappy.  Or you wrote it but mistyped the definition.  It is not a function that's implemented in one of the standard libraries, you have to provide it.  The window procedure is what you use to give a window custom behavior.


text:
Q: Which is the best way to add Google Calendar API scope for GCE service account used by docker container? Which is the best way to add Google Calendar scope/permissions to a service account used by an application (Spring Boot) running inside a container in a Google Compute Engine Container-Optimized OS?
I have read similar SO's but without success and many didn't run docker inside their GCE or didn't use the Google Calendar API. Also, I have enabled the Calendar API for my cloud project but didn't help.
When I start up a GCE COS instance with my Spring Boot container it doesn't seem to have the required scope for the Google Calendar API since I get a 403 Forbidden whenever my application tries to use the calendar API.
403 Forbidden POST https://www.googleapis.com/calendar/v3/calendars/test@gmail.com/events

test@gmail.com in this case is already configured to allow requests from the default service account that my GCE is using, but it still results in 403.
Here is the code for where my Spring Boot configures a GoogleCredentials:
GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(CalendarScopes.CALENDAR));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(googleCredentials);
this.client = new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(), new GsonFactory(), requestInitializer).setApplicationName("AppName").build();

and this triggers the error:
client.events().insert(calendarId, event).execute();

The only way I managed to fix this was to update the scopes of the default service account used by my GCE with gcloud:
gcloud compute instances set-service-account <gce instance name> --service-account someunique_id@developer.gserviceaccount.com --scopes https://www.googleapis.com/auth/calendar,<more scopes...>

However, this must be done for each created instance and the service account cannot be used by any running instance if one needs to update the scopes for the newly created instance. Is there a better way or a different way to get calendar scope and permissions for a docker container inside a GCE?
Note: Strangely enough, when I copy the service account credential JSON and use it locally it works. Shouldn't this be the exact same service account which my docker container is using and if so, why doesn't it work inside GCE?


text:
Q: Why can't i able to access the Current.Application property under Async Call? I have a button to download some data from the database. I am trying to make this button call event a asynchronous one.
Under button click event i am calling the async method
       Public Delegate Function delAsyncMethodCaller()

       **ButtonClick Method**
        Dim obj As New delAsyncMethodCaller(AddressOf downloadReport)
        Dim iAr As IAsyncResult = obj.BeginInvoke(New AsyncCallback(AddressOf AsyncComplete), Nothing)

       Public Function downloadReport()
       Dim objMargin As New clsOMACommon ---Getting Null Reference Exception
        ------Some Operation--------
       End Function

       Public Class clsOMACommon
       Public strConn As String = Current.Application("ConnectionString").ToString.Trim --->The Current.Application is Nothing.
       Public strDBOwner As String = Zurrent.Application("strDBOwner").ToString.Trim
       ------Some Operation------------
       End Class

So when i am calling the async method, inside which i am initializing an object where i am getting an null reference exception because of Current.Application is Nothing.
How can i fix this?


text:
Q: Datagrid in Compact Framework - format cell I would like to format (cell background color for a whole row) a gridview in Compact Framework.
It would not be something like alternating row style, but it would depend on some data the datasource has. So it's like ex.: one row out of total 4 rows for the dt.
What is the simplest way?
Do i need to override Paint() ?

A: There's a pretty extensive example of customizing the CF DataGrid's formatting on Codeplex.


text:
Q: loop a canvas animation co-ordinates I am new to HTML5 canvas and been practicing it for a while.
I've made a particle style canvas where particles float in y axis.
i just need to figure out that when a particle goes out of the cavnas, it needs to be looped again.
here is the fiddle,
Kindly have a look please : )
Here is what i have done so far ==
var canvas = document.getElementById('canvas');
        //*****************************************
        //set context
        var ctx = canvas.getContext('2d');

        //canvas dimensions
        var w = window.innerWidth;
        var h = window.innerHeight;
        canvas.width = w;
        canvas.height = h;

        //*****************************************
        //Lets create an array of particles
        var particles = [];
        for(var i = 0; i < 50; i++)
        {
          //This will add 50 particles to the array with random positions
          particles.push({
            x: Math.random()*w, //x-coordinate
            y: Math.random()*h, //y-coordinate
          })
        }

        //lets create a random particle posiition function
        function randomPosition(){
                this.x = Math.random()*w;
                this.y = Math.random()*h;
        }

        //*****************************************
        //lets animate the particle
        var x =100; var y=100;
        function draw(){
                  //*****************************************
                  //lets paint the canvas with gradient colors
                  ctx.rect(0,0,w,h);
                  // add linear gradient
                  var grd = ctx.createLinearGradient(0, 0,0, h);
                  // light blue
                  grd.addColorStop(0, '#1695A3');
                  // dark blue
                  grd.addColorStop(1, '#B5E6D7');
                  ctx.fillStyle = grd;
                  ctx.fill();

                  //Lets draw particles from the array now
                  for(var t = 0; t < particles.length; t++)
                  {
                        var p = particles[t];

                        ctx.beginPath();
                        ctx.fillStyle = "#ACF0F2";
                        ctx.arc(p.x, p.y, 2, Math.PI*2, false);
                        ctx.fill();

                    //p.x++;
                    p.y--;

                    if(p.y < 0){

                          y = Math.random()*h;
                    }

                  }
        }
        //draw();
        setInterval(draw,10);

Link ----------------------------------
http://jsfiddle.net/wangel12/cBra2/

A: Given a particle (p), here's how to test if it's moved off-canvas and then recycle it:
var radius=2;

if(
    p.x < -radius ||
    p.x > canvas.width+radius ||
    p.y < -radius ||
    p.y > canvas.height+radius
){
    p.x = Math.random()*canvas.width;
    p.y = Math.random()*canvas.height;
}


text:
Q: Error in Signature Verification using C# on OpenShift I am not very good in .net but unfortunately need to work on existing .net code where RSA Signature verification is done using Middleware class in Visual Studio. The code works fine in my Visual Studio but fails on OpenShift .net Core 3.1 image with below error:
[16:47:16 ERR] Stack Trace :
  at CallSite.Target(Closure , CallSite , HttpClient , Object )
  at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1) in /_/src/System.Linq.Expressions/src/System/Dynamic/UpdateDelegates.Generated.cs:line 27

Also I see the request path "" does not match the path filter Error in serilogs. If comment (app.UseMiddleware<MSSOMiddleware.MSSOMiddleware>) code works fine in OpenShift but does not verify the sign.
        app.UseHsts();
        app.UseHttpsRedirection();
        app.UseSerilogRequestLogging();
        //app.UseMiddleware<MSSOMiddleware.MSSOMiddleware>();
        app.UseMvc();

As I am not very good in .net could someone help to understand what that error belongs to?


text:
Q: Docker image dns issue, name solve failed When I run a latest ubuntu image as a container, its apt-get update failed.
It showed me a "Temporary failure resovling 'archive.ubuntu.com'".
Then I tried the solution as below
echo "91.189.92.201 archive.ubuntu.com" >> /etc/hosts
But this can only work for "archive.ubuntu.com" and only for once, it cannot solve other name solve.
If i want the container to link any website, i need to do the similar work as above to add the website's ip address and name to /etc/hosts/
I doubt it was a dns problem, so I tried the solution as below.

By adding "DOCKER_OPTS="--dns   --dns", and the result was nothing like i wanted.

I want the containers in Ubuntu docker can connect to every website, i thought it would be a problem about that the container doesn't have the ability to resolve the website names.

A: 1.please make sure that you can access 8.8.8.8 on the docker host itself.if can't,change 8.8.8.8 to a valid dns server address.
2.check iptables. iptables-save should have one rule:
iptables -t nat -A POSTROUTING -o docker0 -j MASQUERADE
to enable container SNAT and DNAT.


text:
Q: How do I in an Android Imageview, replace one colour with another (black to white) in the xml? How do I in an Android Imageview, replace one colour with another (black to white) in the xml?
I've placed 3 images in a horizontal linearlayout, each image has a transparent background, but is mainly the colour black. I'd like to replace the colour of each of these images to white from within the Android xml.
I don't know how to do this, how would you suggest to accomplish this?
My code so far is below:
 <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="230dp">

                    <ImageView
                        android:id="@+id/imageview_se"
                        android:layout_marginTop="5dp"
                        android:layout_marginLeft="10dp"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:scaleType="fitXY"
                        android:src="@drawable/search"
                        android:backgroundTint=""/>

                    <ImageView
                        android:id="@+id/imageview_hea"
                        android:layout_marginTop="5dp"
                        android:layout_marginLeft="10dp"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:scaleType="fitXY"
                        android:src="@drawable/heart"/>

                    <ImageView
                        android:id="@+id/imageview_menu"
                        android:layout_marginTop="5dp"
                        android:layout_marginLeft="10dp"
                        android:layout_width="30dp"
                        android:layout_height="30dp"
                        android:scaleType="fitXY"
                        android:src="@drawable/menu" />

                    </LinearLayout>

My icons:

A: You're talking about changing the source (android:src) of the ImageView to white, right? Not the background color? If so, you can't do this in xml, you'll have to change the color programatically.
ImageView seImageView = (ImageView) findViewById(R.id.imageview_se);
ImageView heaImageView = (ImageView) findViewById(R.id.imageview_hea);
ImageView menuImageView = (ImageView) findViewById(R.id.imageview_menu);

seImageView.setColorFilter(Color.parseColor("#ffffff"));
heaImageView.setColorFilter(Color.parseColor("#ffffff"));
menuImageView.setColorFilter(Color.parseColor("#ffffff"));

A: Use this method to convert your drawable to white or any other color and apply that drawable to your image view,
public static Drawable convertColorDrawable(int resource, int color, Context context) {
        final Drawable drawable = context.getResources().getDrawable(resource);

        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

        return drawable.mutate();
}

Example:
ImageView imageView1 = (ImageView) findViewById(R.id.imageview_se);

seImageView.setImageDrawable(convertColorDrawable(R.drawable.search, android.R.color.white, context));


text:
Q: Do Cobalt support "qual-e"(YouTube Qualification Engine) page?
*

*Can cobalt enter the YouTube Qualification Engine page?
(http://2016.qual-e.appspot.com/)

*If yes, how can I enter this page for testing?

A: qual-e.appspot.com has been updated and the main pages should work properly now. I just confirmed with Cobalt 10.49488, its able to render the Home and Conformance pages.
Not all sub-pages have been updated, see this bug for details: issuetracker.google.com/issues/35339754

A: Yes, you can open Qual-E in Cobalt. Run Cobalt from command line with the following parameters:
./cobalt --allow_http --csp_mode=disable --url=http://qual-e.appspot.com/?enableLogs=1

While the page won't render correctly (YouTube certification team is working to fix that), you can see the results in terminal or Cobalt developer console (press Ctrl-O twice and restart Qual-E).
Here is the sample output:
[1209/152344:INFO:console.cc(49)] [console.log()] Fri Dec 09 2016 15:23:44 GMT-0800 (PST) - [AudioContext] - result: AudioContext supported
[1209/152344:INFO:console.cc(49)] [console.log()] Fri Dec 09 2016 15:23:44 GMT-0800 (PST) - [AudioContext] - value returned: [object AudioContext]

Cobalt team is aware of several gaps between Cobalt feature set and YouTube TV Technical Requirements and going to address them in Q1 2017.


text:
Q: Es6 modules and Angularjs 1.x I'm using Angularjs and ES6 modules together for the first time and one big question is pissing me off:
How can I retrieve Angular API as es6 modules?
I found this code here:
System.config({
  meta: {
    'components/angular/angular': { format: 'global', exports: 'angular' },
    'components/angular-mocks/angular-mocks': { deps: ['angular'] },
    'components/angular-touch/angular-touch': { deps: ['angular'] },
    'components/angular-animate/angular-animate': { deps: ['angular'] },
    'components/angular-aria/angular-aria/angular-aria': { deps: ['angular'] },
    'components/angular-messages/angular-messages': { deps: ['angular'] },
    'components/angular-i18n-en-gb/angular-i18n/angular-locale_en-gb': { deps: ['angular'] },
    'components/angular-ui-router/angular-ui-router/release/angular-ui-router': { deps: ['angular'] },
  },
  map: {
    'app': 'app-compiled',
    'text': 'components/plugin-text/text',
    'json': 'components/plugin-json/json',
    'lodash': 'components/lodash/dist/lodash',
    'angular': 'components/angular/angular',
    'angular-mock': 'components/angular-mocks/angular-mocks',
    'angular-touch': 'components/angular-touch/angular-touch',
    'angular-animate': 'components/angular-animate/angular-animate',
    'angular-aria': 'components/angular-aria/angular-aria',
    'angular-messages': 'components/angular-messages/angular-messages',
    'angular-i18n-en-gb': 'components/angular-i18n/angular-locale_en-gb',
    'angular-ui-router': 'components/angular-ui-router/release/angular-ui-router',
    'rtts-assert': 'components/assert/src/assert',
  }
});

which I suppose is doing what I need, but someone can explain me how it works?


text:
Q: Kubernetes on single Windows Server Core node cluster My understanding is that Kubernetes is more efficient UI for managing large clusters of containers, otherwise you're stuck with the command line. As of August 2018, It seems multi-platform support on Docker for Windows is still experimental (https://github.com/moby/moby/issues/33850, https://github.com/docker/for-win/issues/2079). Running any Linux image with the --isolation hyperv after pulling with the --platform linux switches doesn't work if not running on expermintal flag. How to enable to experimental flag on Docker for Windows Server core isn't documented. So setting up a single node kubernetes cluster on Windows Server 1803+ for QA purposes probably isn't well supported or even documented. Being an exclusive Windows shop, having to use a Kubernetes on Linux doesn't seem to make sense especially when the whole point of using Docker is to automate environments. What's the point of making environment configuration automatic when you still need to administer a Linux server.
How do you setup Kubernetes on Windows Server Core 1803 as a single node cluster?

A: You can quite easily set up one node Kubernetes cluster on Windows using minikube. You can use a native hypervisor (Hyper-V) if you want, but it is more recommended to use VirtualBox at this time.
In both cases, a Linux virtual machine will run on your server, and you will be able to access it with the native version of kubectl to manage the cluster.
Here are two manuals that can help you to do that (I can guess it will work on the Windows Server in the same way):

*

*Tutorial : Getting Started with Kubernetes on your Windows Laptop with Minikube

*Minikube on Windows 10 with Hyper-V
Here is an explanation of how you can use Windows server as a worker node in Kubernetes:

*

*Using Windows Server Containers in Kubernetes

*Kubernetes on Windows
Microsoft announces that the next version of Windows Server will have better support of Kubenetes and it's ready for testing:

*

*Windows Server 2019 will feature Linux and Kubernetes support


text:
Q: How does MarkLogic Rewriter uri pattern matching actually work? I'm looking at this example from: https://docs.marklogic.com/10.0/rest:matching-request
Specifically, this code:
  xquery version "1.0-ml";

  import module namespace rest="http://marklogic.com/appservices/rest"
  at "/MarkLogic/appservices/utils/rest.xqy";

  declare option xdmp:mapping "false";

  let $options :=
    <options xmlns="http://marklogic.com/appservices/rest">
      <request uri="^/shakespeare/(.+)/(.+)" endpoint="/redirect.xqy">
        <uri-param name="__ml_redirect__">/$1/$2</uri-param>
      </request>
      <request uri="^/shakespeare/(.+)" endpoint="/redirect.xqy">
        <uri-param name="__ml_redirect__">/$1</uri-param>
      </request>
      <request uri="^/(.+)/act(\d+)" endpoint="/endpoint.xqy">
        <uri-param name="play">$1.xml</uri-param>
        <uri-param name="act" as="integer">$2</uri-param>
        <param name="scene" as="integer" values="1|2|3" default="1"/>
      </request>
      <request uri="^/(.+)$" endpoint="/endpoint.xqy">
        <uri-param name="play">$1.xml</uri-param>
      </request>
      <request uri="^/(.+)$" endpoint="/delete.xqy">
        <http method="DELETE"/>
        <param name="reason" required="true"/>
      </request>
      <request uri="^(.+)$" endpoint="/options.xqy" user-params="allow">
        <uri-param name="__ml_options__">$1</uri-param>
        <http method="OPTIONS"/>
      </request>
    </options>

  let $uri     := "/shakespeare/hamlet"
  let $accept  := xdmp:get-request-header("Accept")
  let $params  := map:map()

  return rest:matching-request($options, ("uri","method"))

Now, I would have thought that the match would be:
  <request uri="^/shakespeare/(.+)" endpoint="/redirect.xqy">
    <uri-param name="__ml_redirect__">/$1</uri-param>
  </request>

But, instead, the match is:
  <request uri="^/(.+)$" endpoint="/endpoint.xqy">
    <uri-param name="play">$1.xml</uri-param>
  </request>

The reason that I'm asking is that I would like to come up with a rule for this expression, which is actually good regex: ^(\/openapi\/.+.yml)$
However, for 1) that regex is invalid according to MarkLogic, but ^(/openapi/.+.yml)$ is valid, and 2) if /shakespeare/hamlet doesn't match ^/shakespeare/(.+)/(.+), then I don't understand what the regex is supposed to be that would match it.

A: I believe the issue is that when you are executing the code to test in Query Console, it is using the URL of your Query Console request: /qconsole/endpoints/evaler.xqy.
The code example is a little confusing, because it has let $uri     := "/shakespeare/hamlet", but that $uri is not used. I believe the intent was to show you what the request URI would be, and then demonstrate how the rest:matching-request() function would behave.
You can verify that the URI is indeed /qconsole/endpoints/evaler.xqy by executing this:
import module namespace rest="http://marklogic.com/appservices/rest"
  at "/MarkLogic/appservices/utils/rest.xqy";
let $options :=
  <options xmlns="http://marklogic.com/appservices/rest">
    <request uri="/qconsole/endpoints/evaler.xqy" endpoint="/redirect.xqy">
      <uri-param name="__ml_redirect__">/QUERY-CONSOLE-TEST</uri-param>
    </request>
  </options>
return rest:matching-request($options, "uri")

Also, if you configure an invalid regex, the error message for the matches() will reveal what the actual URL is:
import module namespace rest="http://marklogic.com/appservices/rest"
  at "/MarkLogic/appservices/utils/rest.xqy";
let $options :=
  <options xmlns="http://marklogic.com/appservices/rest">
    <request uri="\/" endpoint="/redirect.xqy">
      <uri-param name="__ml_redirect__">INVALID-REGEX-TEST</uri-param>
    </request>
  </options>
return rest:matching-request($options, "uri")

returns:

[1.0-ml] XDMP-REGEX: (err:FORX0002) fn:matches("/qconsole/endpoints/evaler.xqy", attribute{fn:QName("","uri")}{"/"}) -- Invalid regular expression

You can look under the covers and see how the rest module calls rest-impl.xqy methods and perform tests using the implementation functions:
declare namespace rest="http://marklogic.com/appservices/rest";
import module namespace rest-impl="http://marklogic.com/appservices/rest-impl"
  at  "/MarkLogic/appservices/utils/rest-impl.xqy";
let $options :=
  <options xmlns="http://marklogic.com/appservices/rest">
    <request uri="^(/openapi/.+.yml)$" endpoint="/redirect.xqy"/>
  </options>

let $reqenv := rest-impl:request-environment()
let $_ := map:put($reqenv, "uri", "/openapi/foo.yml")
return
  rest-impl:matching-request-wrapper($options/rest:request, $reqenv, "uri")


text:
Q: How to fix random IOException: Sharing violation during import, build or compile? From time to time, when I try to import, build or just compile, randomly Unity says that an:

IOException Sharing violation

I did a small research, but all the answers point to that error, when executing the code, not just build, and I say that is Random because It happens from time to time and every time the .dll in the Library folder that is marked in the Error, is completely different.

A: As some of the comments said, the error stopped appearing once I disabled the "Ransom/Encryption Protection" from my Antivirus (In this case Kaspersky) and also disabled it in the Windows options.

A: This can also happen, if a program interfers with itself in anyway, for example by having several projects run in parallel or a crashed instance holding onto a handle. Other candidates for handles might be Editors, other Background processes getting handles (e.g. thumbnail generators etc.).
Debugging should happen with a system tool to look at handles. Under windows for example ProcessExplorer(https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer) or Handle (https://learn.microsoft.com/en-us/sysinternals/downloads/handle). Set a breakpoint and then look at what caused the sharing violation.
Prerequisit is a clean software, meaning your own opened handles should be closed once they go out of scope. Some languages provide constructs for that, for example C#s using. Use them to preven dangling buffers.


text:
Q: C#: Trying to use control elements in different class - "object reference is required" I am brand new to C# (I apologise if my question is noobish - I'm teaching myself, so it's a bumpy process). I am trying to develop a winform and since some of the methods are pretty long, I am trying to keep it in a couple classes. This is what I'm kind of hoping to achieve:
public partial class formMainForm : Form
{
    public formMainForm()
    {
        InitializeComponent();
    }

    private void UpDown1_ValueChanged(object sender, EventArgs e)
    {
        longCalculations.LongMethod1();
    }
}

public class longCalculations
{
    private void LongMethod1()
    {
        // Arbitrarily long code goes here
    }
}

I'm doing this in an attempt to keep the formMainForm class tidy and be able to split any calculations into manageable chunks. However, I'm encountering problems with using form controls (e.g. check boxes, numeric up-down controls, etc.) in my non-form classes.
If I leave them as is (e.g. CheckBox1) I get a the name does not exist in the current context error. I searched around and I found that it's because that box is defined in a different class. However, if I change it to formMainForm.CheckBox1, the error is now an object reference is required for the non-static field, method or property. Again, I looked around and it appears that that is due to the form initialization method not being static.
If I change public formMainForm() to static formMainForm(), the error now moves to InitializeComponent(); and I do not know where to go from here. I also tried making an instantiation of the formMainForm() method, but that didn't do anything (the code I attempted to use is below. I found it somewhere on this site as an answer to a similar problem).
private void formLoader(object sender, EventArgs e)
{
    shadowrunMainForm runForm = new shadowrunMainForm();
    runForm.Show();
}

How can I use the formcontrol names in other classes?
P.S. It is my first post here - I am super sorry if I have missed this question already being asked somewhere. I did search, but I didn't find what I was looking for.
EDIT
It seems I hadn't made myself clear - this was just an example of code and my problem is with the second class, not the first one. I have now simplified the code to:
public partial class formMainForm : Form
{
    public formMainForm()
    {
        InitializeComponent();
    }
}

public class longCalculations
{
    private void LongMethod1()
    {
        List<CheckBox> listOfBoxes = new List<CheckBox>();
        listOfBoxes.Add(CheckBox1);
        // The code displays an "object reference is required for the non-static field, method or property" error at this stage. Changing the "CheckBox1" to formMainForm.CheckBox1 doesn't help
        // Arbitrarily long code goes here
    }
}

LongMethod1 works perfectly fine when placed in the formMainForm partial class. Moving it to the other form makes it unable to take data from those checkboxes.

A: I believe this line longCalculations.LongMethod1(); is throwing error cause you are trying to access a instance method as if it's a static method and as well it's defined as private method which won't be accessible outside the class. You need to create an instance of longCalculations class before accessing any of it's member or method(s) and mark the method public like
private void UpDown1_ValueChanged(object sender, EventArgs e)
{
    longCalculations ln = new longCalculations();
    ln.LongMethod1();
}

public class longCalculations
{
    public void LongMethod1()
    {
        // Arbitrarily long code goes here
    }
}

(OR) If you really want it to be a static method then define accordingly with static modifier like
public class longCalculations
{
    public static void LongMethod1()
    {
        // Arbitrarily long code goes here
    }
}

Now you can call it like the way you are trying

A: public static class longCalculations
{
    public static void LongMethod1()
    {
        // Arbitrarily long code goes here
    }
}

If you're going to make a call longCalculations.LongMethod1();, then you need to make your class static as such.
Or you leave it as not static method by calling
longCalculations lc = new longCalculations()
lc.LongMethod1();

As for accessing controls in separate classes, you can pass in the form and make the controls public which can be dangerous.
So on your Form.designer.cs, change any control you may have to public modifier. Then you would make a call like this...
private void UpDown1_ValueChanged(object sender, EventArgs e)
{
    longCalculations.LongMethod1(this);
}

public void LongMethod1(Form1 form)
{
    // Arbitrarily long code goes here
    form.label1.Text = someString;
    //more settings and whatnot
}

Or do something like this:
public class longCalculations
{
    public string LongMethod1()
    {
        // Arbitrarily long code goes here

        return myString;
    }
}

longCalculations lc = new longCalculations()
string result = lc.LongMethod1();
this.label1.Text = result;

A: In your other class, you need to have an instance of your formMainForm class:
var myForm = new formMainForm();

Then you can access its members like this:
myForm.CheckBox1.Checked = true;

A: Ideally, your longCalculations class would not attempt to modify the form directly. Instead it would return an object that the form could use to update its controls.
If you need to access the form directly from the longCalculations class, first change the method to accept an instance of your form
public void LongMethod1(formMainForm myForm)

Then you can pass the form itself as a parameter
var calc = new longCalculations();
calc.LongMethod1(this);


text:
Q: Why doesn't this work on iPad? It properly works on all browsers, just on iPad safari.
If I emulate as iPad user agent on the browser, it just works fine.
http://jsfiddle.net/NMcuy/38/embedded/result/
The problem is that If I type text (Add Text), the keyboard in iPad shows, I can press keys, but it doesn't show in the draggable div. Even the default text stays the same.
I don't know that the problem is :(
function newText()
{
var note = new Note();
note.id = ++highestId;

var text = document.createElement('textarea');
text.name = "text";
text.setAttribute("onkeyup", "textAreaAdjust(this)");
text.setAttribute("class", "text");
//text.innerHTML = initialText;
note.contentField.appendChild(text);

note.name = note.id + "_text";
note.left = Math.round(Math.random() * 400) + 'px';
note.top = Math.round(Math.random() * 500) + 'px';
note.zIndex = ++highestZ;
note.saveAsNew();
}

A: According to my research this is a bug/(specific feature) in iOS regarding focus (or delagating focus) events.
This was dropped afterwards.
Mobile Safari Autofocus text field


text:
Q: How to configure Shadow plugin using kotlin dsl I can't figure out how to use the shadow plugin inside a gradle build with kotlin DSL.
All the documentation is using the groovy dsl.
This is the content of build.gradle.kts:
import groovy.lang.GroovyObject
import org.gradle.jvm.tasks.Jar

plugins {
    // Apply the Kotlin JVM plugin to add support for Kotlin.
    id("org.jetbrains.kotlin.jvm") version "1.4.10"

    id("com.github.johnrengelman.shadow") version "6.1.0"
    application
}

allprojects {
    repositories {
        // Use jcenter for resolving dependencies.
        // You can declare any Maven/Ivy/file repository here.
        jcenter()
    }
    group = "com.example"
    version = "1.0-SNAPSHOT"
}

dependencies {
    // Align versions of all Kotlin components
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))

    // Use the Kotlin JDK 8 standard library.
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
}

application {
    mainClass.set("com.example.MainKt")
}

tasks.withType<Jar> {
    manifest {
        attributes(
                mapOf(
                    "ImplementationTitle" to project.name,
                    "Implementation-Version" to project.version)
        )
    }
}

And this is the content for src/main/kotlin/com/example/Main.kt
package com.example

fun main() {
    println("Hello world")
}

But when I try to do gradle build, I get this error:
A problem was found with the configuration of task ':shadowJar' (type 'ShadowJar').
> No value has been specified for property 'mainClassName'.

which I think is weird, since I've already entered the application main class inside the application argument.
I've tried to add this:
tasks.withType<ShadowJar>() {
    mainClassName = "com.example.MainKt"
}

But when I try to build with this option, it complains that it can't find the ShadowJar type.
  Line 22: tasks.withType<ShadowJar>() {
                          ^ Unresolved reference: ShadowJar

What am I doing wrong here?

A: The problem was that I tried to add mainClassName to the ShadowJar task, it should have been added to the application function. Like this:
application {
    val name = "com.cognite.ingestionservice.MainKt"
    mainClass.set(name)

    // Required by ShadowJar.
    mainClassName = name
}

The mainClassName property is deprecated, but is still required by ShadowJar as of version 6.1.0.
mainClass.set() is not necessary when adding mainClassName, but it was in the documentation for gradle 6.7, so I added it anyway.

A: I'd recommend in your simple case to configure default shadowJar and jar tasks (not all tasks of ShadowJar and Jar type, since you are not creating other instances).
tasks {
    jar {
        manifest {
            attributes(
                mapOf(
                    "Main-Class" to "com.example.MainKt", //will make your jar (produced by jar task) runnable
                    "ImplementationTitle" to project.name,
                    "Implementation-Version" to project.version)
            )
        }
    }
    shadowJar {
        manifest.inheritFrom(jar.get().manifest) //will make your shadowJar (produced by jar task) runnable
    }
}

application {
    mainClassName = "com.example.MainKt" //will make run & runShadow tasks work. Have no idea why it can't take main class from jar/shadowJar manifests
}


text:
Q: Laplace transformation: second shifting theorem
I know the answer is $1/(s^2) +e^-6s (2/s^3 -14/s -1/s^2 )$, but can anyone tell me how to evaluate the solution? I really get stuck.

A: You can write $f(t)$ as
$$f(t)=tu(t)+[(t-6)^2-t-8]u(t-6)=tu(t)+[(t-6)^2-(t-6)-14]u(t-6)$$
where $u(t)$ is the step function. Making use of the correspondence
$$\mathcal{L}\{t^nu(n)\}=\frac{n!}{s^{n+1}}$$
and of the shifting property
$$\mathcal{L}\{f(t-t_0)\}=e^{-st_0}\mathcal{L}\{f(t)\}$$
you get
$$\mathcal{L}\{f(t)\}=\frac{1}{s^2}+e^{-6s}\left[\frac{2}{s^3}-\frac{1}{s^2}-\frac{14}{s}\right]$$


text:
Q: React useEffect causing infinite re-render despite passing argument to dependency array The 'myPosts' has an object with multiple posts inside it.. I wanted the user profile to immediately show the post after it is uploaded so I passed 'myposts' in the dependency array.
But the problem is that the component is re-rendering infinitely. How can I make it so that it re-renders once, only when a new post is uploaded? I can't understand why passing 'myposts' in the array is causing infinite renders instead of only once.
  const [myposts, setPosts] = useState([]);
  useEffect(() => {
  fetch('/mypost', {
    headers: {
     cookie: 'access_key',
    },
   })
     .then((res) => res.json())
     .then((data) => {
     // console.log(data);
     setPosts(data.myposts);
  });
 }, [myposts]);

A: When fetch resolves, it modifies myposts, which triggers a fetch because it is listed as dependency of useEffect, which modifies myposts, and so it continues...
It seems that myposts depends on the result of the fetch, not the other way around. So I would suggest removing myposts from the dependency list.

A: The useEffect hook is called when myposts gets updated. In the final .then of your fetch, you're updating it via setPosts. The best way to fix this is by making the dependency array an empty array.
But this won't solve the issue of updating posts from the server, but this can also be done in a periodic function with setInterval. This would result in something like the code below.
const [myposts, setPosts] = useState([]);

const update = fetch('/mypost', {
  headers: {
    cookie: 'access_key',
  },
})
.then((res) => res.json())
.then((data) => {
  // console.log(data);
  setPosts(data.myposts);
});

useEffect(() => {
  update()
  const interval = setInterval(update, 30000)
  return () => clearInterval(interval)
}, []);


text:
Q: Python 3 and TypeError: a bytes-like object is required, not 'str' error Trying to run this code in python 3
def write_file(file_name, data):

    if file_name is None:
        print ('file_name cannot be none\n')
        sys.exit(0)

    with open(file_name, 'ab') as fp:
        if fp:
            fp.seek(0, os.SEEK_END)
            fp.write(data)
            fp.close()
        else:
            print ('%s write fail\n' % file_name)

and seeing this error:
TypeError: a bytes-like object is required, not 'str'

I am not sure how to define data as bytes?

A: Consider changing the file mode from
with open(file_name, 'ab') as fp:
To
with open(file_name, 'a') as fp:
Since 'ab' mode tries to open the file in binary format.

According to https://www.tutorialspoint.com/python3/python_files_io.htm
format: ab
Opens a file for appending in binary format. The file pointer is at
  the end of the file if the file exists. That is, the file is in the
  append mode. If the file does not exist, it creates a new file for
  writing.


text:
Q: Plot training, validation and test set on same plot This is how I segmented the data
(X, y), (X_test, y_test) = mnist.load_data()
X_train, X_val, y_train, y_val = train_test_split(X,
                                                  y,
                                                  test_size=0.1,
                                                  random_state=1)

The below code plots X_train and X_val, I would like to add X_test the plot
history = model.fit(
    x= X_train,
    y= y_train,
    epochs = 10,
    validation_data = (X_val, y_val),
    batch_size = 128
)

from matplotlib import pyplot as plt

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()

Is it also possible to plot the test_loss on top of this to get an overview of all three on the same plot?
There is no history.history['test_loss'].

A: You did not calculate test_loss yet.
You first need to predict some labels using X_test and then calculate the loss based on the predicted values and y_test. Alternatively, you can use evaluate to do that directly:
test_loss = model.evaluate(X_test, y_test)

You cannot plot them together since test_loss is a single value that is calculated once at the end of training and not every epoch like validation.
Nevertheless, you should not use X_test and y_test in training as you will have trained on the whole available data so you can't test anymore.
X_test and y_test are to be used solely at the end of all the steps to test the performance of the model.
The validation data serves the purpuse of "test data" while you are training. After you have done all the training and optimization you can then retrain the network on the combined dataset of train ad validation, and use the resulting network to test it's performace on the test dataset (X_test, y_test)


text:
Q: How to download a file from shared folder in onedrive using c#? I want to download a file from shared folder in my OneDrive using c#
WebClient clientDownload = new WebClient();

StringBuilder requestUri= new StringBuilder();

requestUriDownload2.AppendFormat("https://onedrive.live.com/download?resid={0}",FileId);

clientDownload.DownloadFile(requestUriDownload2.ToString(), @"C:\Users\Junior\Desktop\exammple.zip");

A: I don't see any authentication or authorization logic in your code. Do you have that?


text:
Q: Treating an SQL ResultSet like a Scala Stream When I query a database and receive a (forward-only, read-only) ResultSet back, the ResultSet acts like a list of database rows.
I am trying to find some way to treat this ResultSet like a Scala Stream. This will allow such operations as filter, map, etc., while not consuming large amounts of RAM.
I implemented a tail-recursive method to extract the individual items, but this requires that all items be in memory at the same time, a problem if the ResultSet is very large:
// Iterate through the result set and gather all of the String values into a list
// then return that list
@tailrec
def loop(resultSet: ResultSet,
         accumulator: List[String] = List()): List[String] = {
  if (!resultSet.next) accumulator.reverse
  else {
    val value = resultSet.getString(1)
    loop(resultSet, value +: accumulator)
  }
}

A: I didn't test it, but why wouldn't it work?
new Iterator[String] {
  def hasNext = resultSet.next()
  def next() = resultSet.getString(1)
}.toStream

A: i needed something similar. Building on elbowich's very cool answer, I wrapped it a bit, and instead of the string, I return the result (so you can get any column)
def resultSetItr(resultSet: ResultSet): Stream[ResultSet] = {
    new Iterator[ResultSet] {
      def hasNext = resultSet.next()
      def next() = resultSet
    }.toStream
  }

I needed to access table metadata, but this will work for table rows (could do a stmt.executeQuery(sql) instead of md.getColumns):
 val md = connection.getMetaData()
 val columnItr = resultSetItr( md.getColumns(null, null, "MyTable", null))
      val columns = columnItr.map(col => {
        val columnType = col.getString("TYPE_NAME")
        val columnName = col.getString("COLUMN_NAME")
        val columnSize = col.getString("COLUMN_SIZE")
        new Column(columnName, columnType, columnSize.toInt, false)
      })

A: Because ResultSet is just a mutable object being navigated by next, we need to define our own concept of a next row. We can do so with an input function as follows:
class ResultSetIterator[T](rs: ResultSet, nextRowFunc: ResultSet => T)
extends Iterator[T] {

  private var nextVal: Option[T] = None

  override def hasNext: Boolean = {
    val ret = rs.next()
    if(ret) {
      nextVal = Some(nextRowFunc(rs))
    } else {
      nextVal = None
    }
    ret
  }

  override def next(): T = nextVal.getOrElse {
    hasNext
    nextVal.getOrElse( throw new ResultSetIteratorOutOfBoundsException
  )}

  class ResultSetIteratorOutOfBoundsException extends Exception("ResultSetIterator reached end of list and next can no longer be called. hasNext should return false.")
}

EDIT:
Translate to stream or something else as per above.

A: Iterator.continually(rs.next())
  .takeWhile(identity)
  .map(_ => Model(
      id = rs.getInt("id"),
      text = rs.getString("text")
   ))

A: Utility function for @elbowich's answer:
def results[T](resultSet: ResultSet)(f: ResultSet => T) = {
  new Iterator[T] {
    def hasNext = resultSet.next()
    def next() = f(resultSet)
  }
}

Allows you to use type inference. E.g.:
stmt.execute("SELECT mystr, myint FROM mytable")

// Example 1:
val it = results(stmt.resultSet) {
  case rs => rs.getString(1) -> 100 * rs.getInt(2)
}
val m = it.toMap // Map[String, Int]

// Example 2:
val it = results(stmt.resultSet)(_.getString(1))

A: This sounds like a great opportunity for an implicit class. First define the implicit class somewhere:
import java.sql.ResultSet

object Implicits {

    implicit class ResultSetStream(resultSet: ResultSet) {

        def toStream: Stream[ResultSet] = {
            new Iterator[ResultSet] {
                def hasNext = resultSet.next()

                def next() = resultSet
            }.toStream
        }
    }
}

Next, simply import this implicit class wherever you have executed your query and defined the ResultSet object:
import com.company.Implicits._

Finally get the data out using the toStream method. For example, get all the ids as shown below:
val allIds = resultSet.toStream.map(result => result.getInt("id"))

A: Here is an alternative, similar to Sergey Alaev's and thoredge's solutions, for when we need a solution which honors the Iterator contract where hasNext is side-effect free.
Assuming a function f: ResultSet => T:
Iterator.unfold(resultSet.next()) { hasNext =>
  Option.when(hasNext)(f(resultSet), resultSet.next())
}

I've found it useful to have as map "extension method" on ResultSet.
implicit class ResultSetOps(resultSet: ResultSet) {
    def map[T](f: ResultSet => T): Iterator[T] = {
      Iterator.unfold(resultSet.next()) { hasNext =>
        Option.when(hasNext)(f(resultSet), resultSet.next())
      }
    }
  }

A: This implementation, although longer and clumsier it is in better correspondence with the ResultSet contract. The side-effect has been removed from hasNext(...) and moved into next().
new Iterator[String] {
  private var available = resultSet.next()
  override def hasNext: Boolean = available
  override def next(): String = {
    val string = resultSet.getString(1)
    available = resultSet.next()
    string
  }
}

A: I think most of above implementations has a nondeterministic hasNext method. Calling it two times will move cursor to the second row. I would advise to use something like that:
  new Iterator[ResultSet] {
    def hasNext = {
      !resultSet.isLast
    }
    def next() = {
      resultSet.next()
      resultSet
    }
  }

A: Another variant on the above, which works with Scala 2.12:
implicit class ResultSetOps(resultSet: ResultSet) {
 def map[T](f: ResultSet => T): Iterator[T] =
  Iterator.continually(resultSet).takeWhile(_.next()).map(f)
}


text:
Q: Adding Input data validation to accept only integer values greater than 0 Im simulating a vending machine and would like to set the product quantity text box to only accept values greater than 0. when i enter -1 my program accepts this value and displays it which i dont want.can someone help please
code is:
//create a new Employee object
    try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
       {
            Products newProd = new Products(this.textProdID.Text);
            newProd.ProductName= this.textProdName.Text;
            newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
            newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
            ProductList.Add(newProd);
            MessageBox.Show(newProd.ProdName + " has been added to the product list");
        }
     catch
     {
        MessageBox.Show("Format entered into text box Is incorrect please check and try again");
     }

A: You should add the Quantity range validation as per your specification - see the code snippet shown below:
//create a new Employee object
    try // Exception handling to ensure that incorrect data type cannot be entered into text box creating a new product
       {
            Products newProd = new Products(this.textProdID.Text);
            newProd.ProductName= this.textProdName.Text;
            newProd.ProductQuantity= Convert.ToInt32(this.textProdQuantity.Text);
            // add the input range validation
            if (newProd.ProductQuantity<=0) throw new ArgumentException ("Quantity must be a positive number.");

            newProd.ProductPrice= Convert.ToDouble(this.textProdPrice.Text);
            ProductList.Add(newProd);
            MessageBox.Show(newProd.ProdName + " has been added to the product list");
        }
     catch
     {
        MessageBox.Show("Format entered into text box Is incorrect please check and try again");
     }

Another solution is just to show a MessageBox with error message if validation fail and return. Further performance optimization can be achieved by using TryParse() instead of Convert method, but considering relatively simple task, both solutions pertinent to this case will suffice the purpose. As a general recommendation, consider adding the input validation to the Control event (e.g. TextBox.TextChanged +=(s,e)=>{ // validation};
Also, pertinent to your case, consider setting the object to null in validation fail.
Hope this will help. Best regards,


text:
Q: How to insert ahead an element to an embedded array? How to insert blow document
  {
      "author": "Vic Zhao",
      "text":  "hell..............."
  }

into blow document as first element of embedded array comments
{
   name: 'Me',
   comments: [{
      "author": "Joe S.",
      "text": "I'm Thirsty"
   },
  {
      "author": "Adder K.",
      "text":  "old content"
  }]
}

A: you can use the prepend operation http://www.rethinkdb.com/api/#js:document_manipulation-prepend
r.table(...).get(...).update({
    comments: r.row('comments').prepend(newEntry)
  }).run(conn, callback)

Where newEntry must be replaced by the data you want to insert.


text:
Q: Validating a yum repository for dependencies I am trying to create a custom rhel5.5 repository for my usage and I am having a hard time validating if I have all the dependencies for every package in my repository.
What I would want to do is do a yum install in dry run on every package in my repository to see if all the dependencies are available.
Is there an easy way to do that?

EDIT
I've found the answer.
Download yum-utils

yum install yum-utils

and do a repoclosure

repoclosure

It will find all missing dependencies of the repositories that you have set in your /etc/yum.repo.d/*

A: yum install yum-utils
and do a repoclosure
repoclosure
It will find all missing dependencies of the repositories that you have set in your /etc/yum.repo.d/*


text:
Q: Why is this loop destroying my memory? I have this function in my MMF class
    void Clear() {
        int size = SizeB();
        int iter = size / sysInfo.granB;
        for (int i = 0; i < iter; i++) {
            auto v = (char*)MapViewOfFile(hMmf, FILE_MAP_READ | (write ? FILE_MAP_WRITE : 0), 0, i * sysInfo.granB, sysInfo.granB);
            std::memset(v, 0, sysInfo.granB);
            UnmapViewOfFile(v);
        }
    }

So what it does is go through the whole file in smallest addressable chunks (64k in this case), maps the view, writes 0's, unmap, repeat. It works allright and is very quick but when I use it, there is some phantom memory usage going on.
According to windows task manager, the process itself is using just a few megabytes but the "physical memory usage" leaps up when I use it on larger files. For instance, using this on a 2GB file is enough to put my laptop in a coma for a few minutes, physical memory usage goes to 99%, everything in task manager is frantically reducing memory and everything freezes for a while.
The whole reason I'm trying to do this in 64k chunks is to keep memory usage down but the chunk size doesn't really matter in this case, any size chunks * n to cover the file does the same thing.
Couple of things I've tried:

*

*flushing the view before unmapping - this makes things terribly slow, doing that 2gb file in any size chunks takes like 10 minutes minutes.

*adding a hardcoded delay in the loop - it actually works really good, it still gets it done in seconds and the memory usage stays down but I just really don't like the concept of a hardcoded delay in any loop

*writing 0's to just the end of the file - I don't actually need to clear the file but only to force it to be ready for usage. What I mean is - when I create a new file and just start with my random IO, I get ~1MB/s at best. If I open an existing file or force write 0's in the new file first, I get much better speeds. I'm not exactly sure why that is but a user in another thread suggested that writing something to the very end of the file after setting the file pointer would have the same effect as clearing but from testing, this is not true.

So currently I'm trying to solve this from the angle of clearing the file without destroying the computers memory. Does anybody know how to appropriately limit that loop?

A: So here's the thing. When you MapViewOfFile, it allocates the associated memory range but may may mark it as swapped out (eg, if it hasn't already been read into memory). If that's the case, you then get a page fault when you first access it (which will then cause the OS to read it in).
Then when you UnmapViewOfFile, the OS takes ownership of the associated memory range and writes the now-not-accessible-by-userspace data back to disk (assuming, of course, that you've written to it, which marks the page as "dirty", otherwise it's straight up deallocated). To quote the documentation (that I asked you to read in comments): modified pages are written "lazily" to disk; that is, modifications may be cached in memory and written to disk at a later time.
Unmapping the view of the file is not guaranteed to "un-commit" and write the data to disk. Moreover, even CloseHandle does not provide that guarantee either. It merely closes the handle to it. Because of caching mechanisms, the operating system is entirely allowed to write data back to disk on its own time if you do not call FlushViewOfFile. Even re-opening the same file may simply pull data back from the cache instead of from disk.
Ultimately the problem is

*

*you memory map a file

*you write to the memory map

*writing to the memory map's address range causes the file's mapping to be read in from disk

*you unmap the file

*unmapping the file "lazily" writes the data back to disk

*OS may reach memory stress, sees that there's some unwritten data that it can now write to disk, and forces that to happen to recover the physical memory for new allocations; by the way, because of the OS lazily flushing, your IO is no longer sequential and causes spindle disk latency to drastically increase

You see better performance when you're sleeping because you're giving the OS the opportunity to say "hey I'm not doing anything... let's go ahead and flush cache" which coerces disk IO to be roughly sequential.


text:
Q: How can i re-set the frame-rate of avi file after its done? I had coded a program that records a screencast using AviFile Lib and set the framerate, but i need to adjust the framerate after the recording its done. How can i re-set the header of the avi-file changing the frame-rate of the avi file created?
Thanks in advance.

A: There is a library and sample app over on codeplex, it may help: http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library


text:
Q: SQL (bigquery) - SUM continues values with start/stop DATETIME within time interval Given the following Table 1 that represents continues drug administration in a steady rate:

row
id
starttime
endtime
drug_total_amount

1
21
2163-04-13T03:00:00
2163-04-13T06:00:00
99

2
21
2163-04-13T16:00:00
2163-04-13T23:00:00
540

3
21
2163-04-14T02:30:00
2163-04-14T17:00:00
308

4
21
2163-04-14T17:00:00
2163-04-14T20:30:00
72

5
21
2163-04-14T20:40:00
2163-04-15T00:00:00
40

6
6
2163-04-14T17:00:00
2163-04-14T20:30:00
72

7
6
2163-04-14T20:40:00
2163-04-15T00:00:00
39.75

8
6
2163-04-15T00:00:00
2163-04-15T01:00:00
13.5

9
6
2163-04-15T01:00:00
2163-04-15T02:00:00
9

And Table 2 that represents events with timestamps:

row
id
event
event_time

1
21
1
2163-04-14T17:30:00

What is the most efficient way to sum administrated values to a specific id in a given time interval prior to the event?

For example:
I want to sum a drug amount for a 24 hour interval before event id 1 (pre_24_hours_drug) -
The relevant rows in table 1 are 2-4 (per id and time range):

*Only the partial amount between 17:00 and endtime (~424)

*Whole amount (308)

*Only the partial amount between starttime and 17:00 (~10)

the result should be:

row
id
event
event_time
pre_24_hours_drug

1
21
1
2163-04-14T17:30:00
742.5714286

A: If I understand correctly, you can use a join to get all the matching rows.  The following should get all overlaps:
select t2.*, t1.*
from t2 join
     t1
     on t2.id = t1.id and
        timestamp_add(t2.event_time, interval -1 day) < t1.end_time and
        t2.event_time > t1.start_time;

Now the trick is to prorate the amounts and sum:
select t2.event, t2.event_time,
       sum(t1.drug_total_amount *
           timestamp_diff(second,
                          least(t2.event_time, t1.end_time),
                           greatest(timestamp_add(t2.event_time, interval -1 day), t1.start_time)
                         ) /
           timestamp_diff(second, t1.start_time, t1.end_time)
          ) as drug_amount
from t2 join
     t1
     on t2.id = t1.id and
        timestamp_add(t2.event_time, interval -1 day) < t1.end_time and
        t2.event_time > t1.start_time
group by t2.event, t2.event_time;

A: Below is for BigQuery Standard SQL
#standardSQL
select t2.id, t2.event, t2.event_time,
  sum(t1.drug_total_amount
    / timestamp_diff(t1.endtime, t1.starttime, second)
    * timestamp_diff(
      least(t2.event_time, t1.endtime),
      greatest(timestamp_sub(t2.event_time, interval 24 hour), t1.starttime),
      second)
  ) as pre_24_hours_drug
from `project.dataset.table2` t2
join `project.dataset.table1` t1
on t1.id = t2.id
and t1.starttime < t2.event_time
and t1.endtime > timestamp_sub(t2.event_time, interval 24 hour)
group by t2.id, t2.event, t2.event_time

If to apply to sample data from your question - the output is


text:
Q: How to fetch selective text data from a webpage using beautifulsoup? I have to fetch data from the following webpage.
https://www.snapdeal.com/product/skycandle-purple-magic-mop/624744850271#bcrumbSearch:magic%20mop
I have also attached a screenshot of the page.
My goal is to fetch the reviews entered by the buyer's in the "Customer Reviews" section that can be found by scrolling down a little.
Screenshot of the 'Customer Reviews' section
import urllib.request

wiki = "https://www.snapdeal.com/product/skycandle-purple-magic-mop/624744850271#bcrumbSearch:magic%20mop"

page = urllib.request.urlopen(wiki)

from bs4 import BeautifulSoup

soup = BeautifulSoup(page)

#for printing comments
comm = soup.find_all("div", {"class" : "reviewareain clearfix"})

print (comm)

But I do not get any output when I run this program. The class name and tags that i have mentioned, I used 'inspect element' on my chrome browser to find out the same. I guess I have selected the wrong class-name due to the multiple nested <div> tags in the structure of the html
I am new to python and so, a simple and comprehensive answer will be appreciated. Also, please suggest some good online material to study beautifulsoup, apart from the official documentation.


text:
Q: Spark Structured streaming getting incorrect number of input rows when using StreamingQueryListener QueryProgressEvent I am facing issue in using StreamingQueryListener to identify number of input row, I am using
queryProgress.progress().numInputRows()
I get proper count when there is no other action apart from write, but the moment I add certain actions such as df.count or df.isEmpty() my number of input rows count get disrupted.
Any help is highly appreciated
EDIT
Below code works
df.writeStream().outputMode("append").foreachBatch(new VoidFunction2<Dataset<Row>,Long>(){
  @Override
  public void call(Dataset<Row> streamDataset, Long batchId) throws Exception {
    streamDataset.write().mode(SaveMode.Append).save("namesAndFavColors.parquet");
  }
}).start();

This gives wrong count
df.writeStream().outputMode("append").foreachBatch(new VoidFunction2<Dataset<Row>,Long>(){
  @Override
  public void call(Dataset<Row> streamDataset, Long batchId) throws Exception {
    streamDataset.count();
    streamDataset.write().mode(SaveMode.Append).save("namesAndFavColors.parquet");
  }
}).start();

Note
Please ignore write() code, in real scenario data is being written to mysql

A: When you are defining more than just one action as in
streamDataset.count();
streamDataset.write().mode(SaveMode.Append).save("namesAndFavColors.parquet");

Spark creates two "seperate" streams that each consume same data. However, both streams are calling the onQueryProgress. This happens at the same time as those two streams are wrapped into the same foreachBatch.
In your particular case you will therefore see twice as much data in your NumInputRows compared to the output of count.
The factor will increase depending on the amount of actions you have.


text:
Q: Deselect one item with VBA in a pivottable that is added to the data model This is my first time posting here and I am new to VBA.
As mentioned in the title I want to deselect one item for multiple (in this example two) filters of multiple pivottables (which are all in one sheet) which are added to the data model. The data of the pivottable is added to the data model so the values can be set to distinct counts (which is not possible without adding the data to the data model).
The reason I want to deselect one item is actually a workaround for what I really want. I add data to the source data (dynamic named range) and refresh the pivottables. But, because there are filters applied to the pivottable the newly added items will not be selected automatically. So, you might think why not use the option "Include new items in manual filter"? Well, because the data of the pivottable is added to the data model this option is grayed out (so it cannot be selected).
Therefore, I am trying to write some code to first select all the items (so the newly added items are added to the manual filter) and then deselect the items I do not want (because I know beforehand which items to deselect as they are already in the first set of data).
I have tried to use the macro recorded, but apparently when items in the manual filter are deselected it records the selected items which remains.
Because the data of the pivottable is added to the data model the code is written differently. The solutions I found, where only applicable for "regular" pivottables.
Find below the code I tried to use. As mentioned in the code the first part works, only the second part does not. Also I have no idea if the property "HiddenItemsList" is the correct one to use.
    Sub DataModel_PivotTable_FilterFields()

    'works - will select all the items in the manual filter
        Worksheets("xxx").PivotTables("PivotTable3").PivotFields( _
            "[xyx].[xxy].[xxy]").VisibleItemsList = Array("")

    'does not work - should deselect the item "zxx" after this part works I will add the other item
    'to be deselected in the array if possible
        Worksheets("xxx").PivotTables("PivotTable3").PivotFields( _
            "[xyx].[xxy].[xxy]").HiddenItemsList = Array( _
            "[xyx].[xxy].&[zxx]")

    End Sub

Could someone please try to help me with this? It would be very much appreciated.

A: Should anyone be interested I found a solution by using slicers. The code that I used was taken from the answer of IG2013. Just change Dim i As Long to Dim i As String if the value of the slicer is a string.


text:
Q: Adding a column to Eloquent Model without Migrate -PHP I have an old project which has been migrated to different servers over years. Hence, I can't run any artisan commands on the project.
I want to add a column "sessiontime" to an existing model User. I added the column in the data base table - ALTER TABLE users ADD COLUMN sessiontime VARCHAR(1025) NULL AFTER session;
In my User Model - User.php I added the following code:
public function setSessiontime($sessiontime)
{
  $this->sessiontime = $sessiontime;
}

public function getSessiontime()
{
  return $this->sessiontime;
}

In one of my Controllers I am doing this:
$user = User::select('id')->where('email', 'a.b@c.com')->first();
$user->sessiontime = "RANDOMString";
$user->save();

But the column in not getting populated.
Is it possible to add a column to an existing table, without having to run artisan migrate?
Thanks

A: This likely due to Laravel's default protection against mass assignment. For any Eloquent model, you have the option of defining either (but not both) a $guarded or $fillable array. The $guarded array works as a blacklist of properties that are not mass-assignable, while the $fillable property works as a whitelist of properties that are mass-assignable.
To solve your issue, you probably just need to add the sessiontime property to your $fillable array:
protected $fillable = [ ..., 'sessiontime'];


text:
Q: NgFor on Object + Create NgModel for each property in NgFor I am facing issue while creating a ngfor on object and my ngfor contains ngModel of each property
Here is the code:
<div *ngFor="let key of objectKeys(todo)">

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key == 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-textarea [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-textarea>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'Date' && key != 'Description'"
              style="margin-top: 15px;">
              <ion-label>{{key}}</ion-label>
              <ion-datetime displayFormat="MM/DD/YYYY hh:mm A" [min]="yesterDayStr"
                 [(ngModel)]="this['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-datetime>
          </ion-item>

 </div>

Expected model string in this ngModel is > todo.title
But property are not going to bind to the respective input
Thanks

A: You should not use this in the template, Change your code as follows,
 <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="['todo.' + key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
 </ion-item>

A: Agree with @Sajeetharan, we don't need to use 'this' and try using 'todo[key]'.
<div *ngFor="let key of objectKeys(todo)">

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key != 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-input type="text" [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-input>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'String' && key == 'Description'">
              <ion-label floating>{{key}}</ion-label>
              <ion-textarea [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-textarea>
          </ion-item>

          <ion-item *ngIf="getObjectDataType(key) == 'Date' && key != 'Description'"
              style="margin-top: 15px;">
              <ion-label>{{key}}</ion-label>
              <ion-datetime displayFormat="MM/DD/YYYY hh:mm A" [min]="yesterDayStr"
                 [(ngModel)]="todo[key]"  [ngModelOptions]="{ standalone : true }"></ion-datetime>
          </ion-item>

 </div>