text:
Q: H2: how to tell if table exists? I'm trying to write Java code that checks to see if an H2 table exists: if it doesn't exist, it first executes a CREATE TABLE query that creates the table before it proceeds any further.
I followed the advice in this Google Groups question but it simply does not work.
If I run the following query:
SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_name = 'word_types'

I get back a single row with a COUNT field which has a value of 0; this indicates that the word_types tables doesn't exist. But when I run:
SELECT * FROM word_types

I get back 0 result sets, but the SQL frontend/GUI that I'm using shows me all the fields/columns that exist in the word_types table. Additionally, when I drill down into my database's list of available tables (using the same GUI), I see word_types exists.
So what is the correct query to use when trying to determine if an H2 table exists or not? Using v1.3.173. Thanks in advance!

A: First: check the case in which you type tables' names. It's very important. word_types and WORD_TYPES are two different tables.
Second: If you want to check if table exists and if it doesn't then create one, I recommend you to use the following example:
CREATE TABLE IF NOT EXISTS TEST(ID INT PRIMARY KEY, NAME VARCHAR(255));

A: There is also a JDBC API which you can use to query the existence of one or more tables.
This is (in theory) more portable than a direct query which uses information_schema.
(In practice, the portability is still somewhat limited by the fact that different DBMS define and use the concepts schema and catalog slightly differently).
This is how it works:
boolean tableExists = false;

Connection conn = getConnection(); // get a DB connection from somewhere
ResultSet rset = conn.getMetaData().getTables(null, null, "WORD_TYPES", null);
if (rset.next())
{
  tableExists = true;
}

Instead of "WORD_TYPES" you can also use SQL-Style wildcards, e.g. "WORD_%".
Note that H2 has a configuration setting DATABASE_TO_UPPER which is set to true per default. So any table name is converted to upper case which is why you need to query for the table in upper case (or set DATABASE_TO_UPPER to false).
Also, using the other parameters (which I have set to null here), you can further restrict the search scope to a specific scema or table type.
The resultset also contains meta-information about the table, if you need that, e.g., the schema or table comment.
See the JavaDoc for a complete list of options and available metadata.

A: If the second query doesn't throw an exception or return any rows, it just means the table exists but is empty.

A: Your above query will return the records count not existence of your table, for that you have to fire the follwing query. This query will return you all table of your Database and from there you can check your "word_types" exists or not.
USE YOURDBNAME
GO
SELECT *
FROM sys.Tables
GO
reply me if it work or not works also

A:     Connection con = getConnection();
    Boolean tableExist = false;
    PreparedStatement preparedStatement = con.prepareStatement("SHOW TABLES FROM INFORMATION_SCHEMA");
        Boolean rq = preparedStatement.execute();
        if(rq) {
                ResultSet rs = preparedStatement.getResultSet();
                while (rs.next()) {
                    if(rs.getString(rs.getRow()).equals("WORD_TYPES")) {
                        isExist = true;
                        break;
                }
            }
        }


text:
Q: Accessibility - React Ensure click events have key events I want to be sure that all my onClick event are next to a onKeyDown event.
I will use eslint-plugin-jsx-a11y to ensure this.
But in code, It is a way to do this generic. I mean, it will be annoying to do all the time:
 if(event.keyCode === 13){
    ...
 }

I would like to have a way to tell an element that in onKeyDown in case that the user use the  execute the function in the onClick. Or a similar solution like
http://www.karlgroves.com/2014/11/24/ridiculously-easy-trick-for-keyboard-accessibility/
In angular for instance, I have this clear. Let's go for a directive to do this automatically. But in React I don't know which is the best approach.

eslint rule:
https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md

A: Great solutions here already, but I wanted an option where I didn't have to use decorators or prop-spreading. So I rejigged some of the existing answers into this:
function keyDownA11y(handler) {
  return function onKeyDown(event) {
    if (
      ['keydown', 'keypress'].includes(event.type)
      && ['Enter', ' '].includes(event.key)
    ) {
      handler();
    }
  }
}

usage:

  Hurray!

EDIT: Alternatively, you could use this to make an A11yButton component and just import that. This way, you could get the benefits of cragb's excellent buttonizer solution:
import React from 'react';

export default function A11yButton({
  elementType,
  onClick,
  ...props
}) {
  return React.createElement(elementType, {
    ...props,
    onClick,
    onKeyDown: keyDownA11y(onClick),
    role: 'button',
    // Add other props that might be necessary, like "tabIndex: 0,"
  });
}

Usage:
<A11yButton
  elementType="div"
  onClick={myHandler}
>
  Hurray!
</A11yButton>

A: Another approach without decorators could be to use object spread to add the necessary props to an element:
function buttonize(handlerFn) {
  return {
    role: 'button',
    onClick: handlerFn,
    onKeyDown: event => {
      // insert your preferred method for detecting the keypress
      if (event.keycode === 13) handlerFn(event);
    }
  }
}

and use like so:

click me

A: Finally I only see 2 solutions:
1 I can create a component that encapsulate all those actions... But this is the work of a button. And I want not to open a new way to create buttons in my project, this is just for exceptions and this can create a vicious behave inside the project. And for that we have another component... the button :)
2 create a decorator for the actions.
export function a11yButtonActionHandler(target, key, descriptor) {
    const fn = descriptor.value;
    if (typeof fn !== 'function') {
        throw new Error(`@a11yButtonActionHandler decorator can only be applied to methods not: ${typeof fn}`);
    }

    descriptor.value = function actionHandler(event) {
        if (!event || event.type === 'click' ||
            (['keydown', 'keypress'].includes(event.type) && ['Enter', ' '].includes(event.key))
        ) {
            fn.call(this, event);
        }
    };

    return descriptor;
}

and use the decorator.
@a11yButtonActionHandler
myAction(event) {
 ...
}

A: To simplify Raúl Martíns answer and don't use decorators which are still just a proposal you can also create a simple function out of it:
function isButtonAction(event) {
    return (
        event.type === 'click' ||
        (['keydown', 'keypress'].includes(event.type) &&
            ['Enter', ' '].includes(event.key))
    );
}

then simply check it in your action handler:
function myAction(event) {
    if (isButtonAction(event)) {
        ...
    }
}

A: I suggest you use a state to handle it. For example:
First, initial a state in your component and set the event listener:
getInitialState(){
  window.addEventListener("keypress", this.onKeypresshandler);// if you are not rendering on server side, you cannot bind the listener to the element you want, which doesn't exist yet.
  return{
      isPressed: false
  }
}

Then, change the state when the key keypress event is called:
onKeypresskhandler(e){
    if(e.keyCode === 13){// if the key is enter
      this.setState({isPressed:true})
    }
}

finally, check the state before executing your function
YourFunction(){
  if(this.state.isPressed){// check if the key is pressed
    ... // the code you want to execute
  }
}

It is the simplest way I know. I hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript regular expression for "at least X characters, have a capital letter and a number" I have a regular expression for a password field which I know works perfectly i.e. Must be at least 6 characters in length, have a capital letter, a number and can contain special characters.  When I try to apply this regex within Javascript it doesn't seem to validate.  My Javascript function is below.
function (word) {
    var weakRegEx = new RegExp('(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$');
    var result = weakRegEx.test(word);
    return result;

A: Since you're writing a string literal, you need to escape the \ characters.
You should use a regex literal instead:
var weakRegEx = /(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;


text:
Q: Eclipse not working in Ubuntu 20.04 I can't even run a simple hello world! program in Eclipse.
Let's go step by step. Whenever I write a program and try to save it It shows this error:

And when I try to run the program It shows this error:

I'm so confused and frustrated because I have to run programs every time through terminal javac file.java and java file.
by running java --version I'm getting:
openjdk 17.0.3 2022-04-19
OpenJDK Runtime Environment (build 17.0.3+7-Ubuntu-0ubuntu0.20.04.1)
OpenJDK 64-Bit Server VM (build 17.0.3+7-Ubuntu-0ubuntu0.20.04.1, mixed mode, sharing)

this output and eclipse version is: 19-12


text:
Q: Java socket getting only NUL characters after writing byte array I'm trying to send files in chunks from a client to server via byte arrays. I'm using ObjectInputStream. The write works and the filesize matches but when I open the file, I only get a blank textfile(which when opened in a IDE, shows NUL,NUL,NUL...).
Server code:
try(
    FileOutputStream fileOut = new FileOutputStream(file);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
){
byte[] arr = new byte[chunkSize];
try {
    int len = 0;
    long bytesRead = 0;

    byte[] bytes = new byte[chunkSize];
    int chunkNo = 1;

    while(true)
    {
        len = in.read(bytes,0, chunkSize);
        System.out.println();
        if(len < 0)
            break;

        fileOut.write(arr, 0, len);

        bytesRead += len;

        out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
        String ackReply = (String) in.readObject();

        if(ackReply.equalsIgnoreCase((Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG))){
            if(Server.DEBUG)
                System.out.println(fileName + " send timeout.");

            deleteFile();
            break;
        }else if (ackReply.equalsIgnoreCase(Server.UPLOAD_COMPLETE_MSG)){
            if(bytesRead != fileSize){

                System.out.println(fileName + " File size mismatch");
                deleteFile();
                break;
            }else{
                System.out.println( fileName + " File written");
                break;
            }
        }

    }
}catch (IOException ioe){
    if(Server.DEBUG)
        ioe.printStackTrace();
}

Client code:
 try(
        FileInputStream fileInput = new FileInputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
    ){
        byte[] arr = new byte[chunkSize];
        try {
            int len = 0;
            int bytesRead = 0;
            int chunkCount = 1;
            while((len = fileInput.read(arr, 0, chunkSize)) != -1)
            {
                out.write(arr, 0, len);
                out.flush();

                bytesRead += len;

                }
                    try {
                        System.out.println("wait ack");

                        socket.setSoTimeout(timeout);
                        String ack = (String) in.readObject();
                        System.out.println(ack);

                        if(bytesRead >= fileSize){
                            out.writeObject(Server.UPLOAD_COMPLETE_MSG);
                            System.out.println(Server.UPLOAD_COMPLETE_MSG);
                            break;
                        }else{
                            out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
                        }
                    }catch (SocketTimeoutException e){
                        out.writeObject(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);
                        System.out.println(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);

                        break;
                    }finally {
                        socket.setSoTimeout(0);
                    }
                }
            }

        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }catch (FileNotFoundException fnfe){
        System.out.println("No such file: " + fileName);
    }catch (Exception e){
        e.printStackTrace();
    }
    finally {
        try {
            socket.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

I tried writing the byte array to another file on the client side  and the copy was identical. So the problem must be during sending data over socket.
The Server.X_MSG is just a constant string. I don't know if mixing readobject() and read(bytearray) on the same ObjectInputStream causes any issues though.

A: Maybe it's because fileOut.write(arr, 0, len); use arr and len = in.read(bytes,0, chunkSize); use bytes? They are not the same array.


text:
Q: Odoo V8: Javascript widgets: How to get the settings right? I'm trying to make a custom widget to change the color of a field in a form view.
I found these 2 links:
https://www.odoo.com/nl_NL/forum/help-1/question/can-we-apply-seperate-color-to-partilcular-column-in-tree-view-85372
https://www.odoo.com/nl_NL/forum/help-1/question/how-can-i-extend-a-view-type-e-g-instance-web-listview-extend-89487
I've based my widget on the first link. The difference in my case is that I need to do something in a form instead of a list/tree.
This is how I made it right now:
Name of my module: opcconnectie_v1_1
/static/src/js/hewwidgets.js:
 openerp.opcconnectie_v1_1 = function (instance) {
     instance.web.form.widgets.add('kleuren', 'instance.opcconnectie_v1_1.kleurenwidget');
     instance.opcconnectie_v1_1.kleurenwidget = instance.web.form.widgets.extend({
         window.alert("test if widget is called");
    });
};

views.xml:
<openerp>
<data>
<template id="assets_backend" name="opcconnectie_v1_1 assets" inherit_id="web.assets_backend">
  <xpath expr="." position="inside">
    <script type="text/javascript" src="/opcconnectie_v1_1/static/src/js/hewwidgets.js"></script>
  </xpath>
</template>

<record id="product_template_inherit" model="ir.ui.view">
    <field name="name">product.template.stock.property.form.inherit</field>
    <field name="model">product.template</field>
    <field name="inherit_id" ref="stock.view_template_property_form" />
    <field name="arch" type="xml">
        <xpath expr="//page[@string='Inventory']/group" position="before">
            <group>
                <field name="stocktag_status" widget="kleuren"/>
            </group>
        </xpath>
    </field>
</record>
</data>
</openerp>

openerp.py
'depends': ['base', 'web', 'product'],
'js': ['static/src/js/hewwidgets.js'],

In hewwidgets.js, I've tried to get all the "settings" correct. I'm not sure if they are correct, I don't think so. I've put a window.alert there to see if it does anything.
Later the code needs to be changed to adjust field colors.
The window.alert didn't show, so I'm wondering what's wrong with this.
Anyone who knows how to get the "settings" right?
Is there something wrong with how I "include" the widget in my project?


text:
Q: What's C# threading type? Between three types of threading (kernel-level, user-level and hybrid), which type does C# (or more generally .NET) use?

A: Kernal Thread (1 : 1)
The term "kernel threads" can be used to refer to actual threads that run entirely in kernel space or it can refer to user-space threads scheduled by the kernel. The term "kernel-supported" threads means the latter, threads that run in user-space but are facilitated by the kernel, which usually means the kernel schedules them.
Kernel threads are privileged and can access things off-limits to user mode threads.  Take a look at "Ring (Computer Security)" on Wikipedia.  On Windows, user mode corresponds to Ring 3, while kernel mode corresponds to Ring 0.
User Level Thread (N : 1)
"User-level threads" usually means threads visible to user space. That is, what you create when you call your threading standard's "create thread" function. Generally, the term "user-level thread" is used to mean a thread created by the application code regardless of how it's implemented by the system. It may be a pure user-space thread with little to no kernel support or it may be a thread scheduled by the kernel.
Hybrid Threading (M : N) [WikiPedia]
M:N maps some M number of application threads onto some N number of kernel entities, or "virtual processors." This is a compromise between kernel-level ("1:1") and user-level ("N:1") threading. In general, "M:N" threading systems are more complex to implement than either kernel or user threads, because changes to both kernel and user-space code are required. In the M:N implementation, the threading library is responsible for scheduling user threads on the available schedulable entities; this makes context switching of threads very fast, as it avoids system calls.
.Net thread are user-level thread that uses the Win32 API and wraps it up as a nice Framework!

More details can be found :

*

*Thread (computing)

*Kernel threads vs. Kernel-supported threads vs. User-level threads

*user thread and kernel thread

*Is Thread a Kernel Object ?

A: It's not up to the C# itself, but rather the runtime - CLR.
.Net can be considered to support two modes:

*

*User-land only scheduling (or Windows UMS). In this mode one user land thread can can perform a context switch into another user mode thread without actually changing the kernel thread. This mode adds a lot of coding overhead, but saves precious 10-20 microseconds in a kernel level context switch.

*Hybrid model (most popular by far). In this model managed code requires access to the kernel, such as reading a file. Through a set of API the code execution travels from user-land .NET calls, into the Windows API, into the kernel, driver, HAL layer and physical drive. And back through the call stack fetching the data. If a context switch is initiated by the thread scheduler, then user thread and kernel thread are changed.

Direct kernel mode threading is not allowed, because managed code does not have privileges to run in the kernel mode. It can only call Windows API, which in turn switch into the kernel mode.

If you use a Thread, Task, ThreadPool - CLR uses hybrid model. A hybrid model is used because CLR creates managed object to represent that classes. Any managed code runs in the user-land. However, every thread that is not created as a fibber (see below), be it in a thread pool or not, has got underlying kernel data structures. Kernel data structures are used to hold the thread's kernel state - kernel thread id, create and exit times, process id, start thread address, security access token, dozen of timers, CPU register, kernel stack etc. All these need to be updated during a context switch, but we just take the hit of roughly 10-20 * 10^-6 sec it takes.
If you use a managed wrapper around Ums set of C++ calls (like CreateUmsThreadContext, UmsThreadYield and many others) - CLR attempts to use UMS mode. But this is only specific to the few threads you specifically and manually manipulate. Your application will still use the hybrid model, just a few manually picked threads (fibbers) will be manually yielded between each other in user mode. But even in this mode, at some point OS task scheduler will initiate a kernel thread switch, so you are not stuck executing UMS scheduled threads for ever.
For completeness,

*

*Kernel-mode scheduling is a very low level mechanism that is accessible from the kernel only. What it means is that you can only use it, if you develop OS internals or some sort of a driver. Such scheduling is difficult to use, any mistake and the whole OS is frozen/stuck/crashed/BSODed or transits to any other unpredictable state. Kernel level threading requires enormous development and testing effort. For example, Windows task scheduler or memory management service use kernel mode scheduling. Can you imaging how much time it took to write these components so that they are stable in a highly multithreaded environment?


text:
Q: A Measurable Function is the Pointwise Limits (a.e.) of a Sequence of Cont. Functions
Let $E \subseteq \Bbb{R}$ be a measurable set. If $f : E \to \Bbb{R}$ is a measurable function, then there exists a sequence $\{f_n\}$ of continuous functions $E$ such that $f_n \to f$ pointwise a.e. on $E$.

I think I have a proof; but I am wondering if someone would critique it.

For each $n \in \Bbb{N}$, Lusin's theorem tells us that there exists a continuous function $f_n : E \to \Bbb{R}$ and a closed set $F_n \subseteq E$ such that $f=f_n$ on $F_n$ and $m(E \setminus F_n) < \frac{1}{2^n}$. Let $E_n := \bigcap_{k=n}^\infty F_k$, so $E_n$ is a closed set and therefore measurable. It isn't difficult to show that $\{E \setminus E_n \}_{n=1}^\infty$ is a decreasing sequence of measurable sets and that $E - E_1$ is of finite measure. Hence,
  $$m(E \setminus \bigcup_{n=1}^\infty E_n) = m \left( \bigcap_{n=1}^\infty (E \setminus E_n) \right)$$
$$= \lim_{n \to \infty} m(E \setminus E_n)$$
$$= \lim_{n \to \infty} m \left(\bigcup_{k=n}^\infty (E \setminus F_k) \right)$$
$$ \le \lim_{n \to \infty} \sum_{k=n}^\infty m(E \setminus F_k)$$
$$=\lim_{n \to \infty} \sum_{n=k}^\infty \frac{1}{2^n}$$
$$=0$$
This shows that $E \setminus \bigcup_{n=1}^\infty E_n$ is a set of measure $0$. Moreover, if $x \in \bigcup_{n=1}^\infty E_n$, then there exists some $n \in \Bbb{N}$ such that $x \in F_k$ for every $k \ge n$. This means that $f_k(x) = f(x)$ for every $k \ge n$, so $\lim_{k \to \infty} f_k(x) = f(x)$. Therefore, $f_n \to f$ pointwise a.e. on $E$

How does this look?


text:
Q: How to override "default" navigation bar? On my iOS application, I have the following view controllers navigation scheme on my storyboard

Navigation Controller -> ViewController A -> ViewController B

I'm able to customize the navigation bar on View Controller A but custom navigation bar I designed on interface builder, doesn't show up for View Controller B. It only shows up the "back" button.
Can I define a custom navigation bar for "inner" views on interface builder? I know I could do it programatically, but if I can avoid it, the better.

A: I think you may be missing an important element in your understanding.
The UINavigationBar owned by the UINavigationController is merely a container for each view controller's UINavigationItem. Use this navigation item to add/remove buttons that are specific to each view controller.
Using your own example:

UINavigationController (displays each view controller's navigation item inside its navigation bar) -> UIViewController A (includes UINavigationItem A, which has its own buttons) -> UIViewController B (includes UINavigationItem B, which has its own buttons)

If you want to hide the back button you can do so by adding the following line inside each view controller or in your view controller's superclass:
self.navigationItem.hidesBackButton = true
If you want all view controllers to have the same buttons, you're probably better off creating a UIViewController base class and add the proper buttons to the navigation item programmatically. Make sure all your view controllers inherit from this new subclass.
Hope this helps!


text:
Q: Android ClassNotFound exception when changing view background For my activity, I created a new view and saved it in a public static field. I then set the view with setContentView in the activity. However, whenever I try to change the color of the view from another class, I get a exception as follows:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.TwinBlade.PicturePassword/com.TwinBlade.PicturePassword.LockActivity}: java.lang.ClassNotFoundException: com.TwinBlade.PicturePassword.LockActivity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.TwinBlade.PicturePassword.LockActivity
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
    ... 11 more

java.lang.ClassNotFoundException: com.TwinBlade.PicturePassword.LockActivity
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
    at android.app.ActivityThread.access$600(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:4945)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)

UPDATE:
Here is what i did in my activity
public static View mView;

public void onCreate(Bundle savedInstanceState) {
    mView = new LinearLayout(this);
    mView.setBackgroundColor(Color.argb(0, 0, 0, 0));
    setContentView(mView);
}

And to change the color of the view from another class:
LockActivity.mView.setBackgroundColor(Color.argb(255, 0, 0, 0));

The activity is added in the manifest and can be launched.
Any help would be appreciated

A: There is an issue with your LockActivity. Make sure that you have added that entry in the manifest file.

A: context.findViewById(); the context is your activity  or you can try to
View view = (View) =LayoutInflater.from(activity.this).inflate(your layout,null)


text:
Q: After a Read Uncommitted query, do I have to set it back to Committed? Imagine executing a query using code similar to this here:
using (SqlConnection TheConnection = GetSqlConnectionNoCatch(SQLConnectionStr))
using (SqlDataAdapter TheDataAdapter = new SqlDataAdapter(SQLStatement, TheConnection) { MissingSchemaAction = SchemaAction })
{
    DataSet TheDataSet = new DataSet();
    TheDataAdapter.SelectCommand.CommandTimeout = SQLTimeout;
    TheDataAdapter.Fill(TheDataSet, TableName);

    return TheDataSet;
}

And imagine having to read a database table that is absolutely getting pounded, non-stop, with writes, which leads to a lot of deadlocks and failures so you have to perform that read using a Read Uncommitted Isolation level.
If my normal query was:
SELECT Field1, Field2 FROM Table WHERE some_type_of_clause

I often see that you would change it to:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT Field1, Field2 FROM Table WHERE some_type_of_clause

OK, so here's what led me to ask this question, this particular link: http://blog.sqlauthority.com/2011/04/17/sql-server-applying-nolock-hint-at-query-level-nolock-for-whole-transaction/
His example has the following:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT *
FROM AdventureWorks.Sales.SalesOrderDetail sod
INNER JOIN AdventureWorks.Sales.SalesOrderHeader soh ON
sod.SalesOrderID = soh.SalesOrderID
ORDER BY sod.ModifiedDate
-- Set isolation level to original isolation level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

Do I need to set it back to READ COMMITTED at the end of my query too?  Or is my read uncommitted only good for that one query?  Or maybe the life of the connection (which examining my code would mean as soon as I return the DataSet, as my Connection closes right then)?
Most examples on the web leave out the 'set it back to original isolation level', so it puzzled me that he included it.  Thanks!

A: The answer here may be helpful: WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
The transaction isolation level is a connection level setting.  This means that any nested stored procedure calls, etc will use your new isolation level setting, but other users/query windows/session from the same user will use the applicable default (or whatever was last set).
In your case, you are not required to set the isolation level back to committed unless you have other statements or data sets to return that shouldn't be using uncommited later in the same session. Resetting is simply a good practice.


text:
Q: Htaccess rewriteCond allows to browse directories Im making a php script with router, and condition of it - write in htaccess file specific code - this one:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

But string RewriteCond %{REQUEST_FILENAME} !-d allows to browse all my directories with all scripts, like example.com/server (my server logic). Without it its pretty good. Is it so neccessary and why it added to script?


text:
Q: Can Ubuntu act as a Domain Controller for multiple OSes? I would like to install Ubuntu server at my church to start testing a few options (to eliminate Microsoft usage). Some PCs use Windows XP, and some use Ubuntu.
I would like the Ubuntu server to be a Domain Controller so that any user account will be able to log on to either a Windows or Ubuntu desktop.
Is this possible?
I would also like to be able to manage accounts from the server? (eg. adding, removing, modifying)

A: Depends on what version of Ubuntu you need to use.
The Samba version is what really matters.
To become a member of Active Directory, you would join the server as described in the documentation for Samba. Then Google how to either become a member server, or clone its data from the ADS, and then reconfigure the smb.conf to be standalone.
To do it without Windows Active Directory (or just domains for NT4 servers)
create the server with a wizard if your not sure, or edit a sample smb.conf in the help/documentation to your requirements (also known as standalone server mode).
It uses LDAP or NIS for its services. (depending which way you choose to setup)
Zentyal has server software (and was based on Ubuntu, previously known as EBOX)
could be worth looking into.
Maybe if you are stuck for which way, always consult Google first, then the Ubuntu community. This way I can assure you you would save yourself some time, plus you are more likely to be helped more quickly if you did some research first.
Anyway for client computers and servers (depending on what OSs you're planning to use, here's a list "based on my personal experience only"). It comes with no warranty, guarantees, it could be fit for reference of my experience, but not for purpose as things change fast in Linux/Ubuntu/Samba.
With that said, here is that list I mentioned.
NT based Windows versions
• Windows XP Professional / Media Center editions
⠀• (works both ways for joining networks, home editions doesn't do server connectivity)
• Windows 7/Vista
⠀• (could work both ways, but needs registry changes to use the standalone properly, but can make the OS slightly less secure.)
• Windows Server 2008 & 2008 R2
⠀• (join its domain, clone the ADS @where possible@ and then unjoin by reconfiguring it to be standalone, using smb.conf @cannot be used as bdc to samba@
(well, unless there's been changes since I last checked, but to my knowledge,then no, it cannot.)
• Windows Server 2003
⠀• (can do same as Windows Server 2008, but has the ability to join either methods, as it's from same code base as XP)
• Windows 2000 Servers
⠀• (the standalone is almost the equivalent of a 2000 Active Directory)
• Windows 2000 Pro
⠀• (can join both but I think it would need for newer ADS versions to be in compatible mode @sometimes explained as not secure@ )
• Windows NT 4.5 Back Office (the upgrade discs, technically not an outright standalone OS)
⠀• (it doesn't have active directory, but used a service before ADS was born called "Back Office", use this reference as the same as NT 4 server)
• Windows NT 4
⠀• (standalone method only, nt4 doesn't have ADS as far as i know)
• Windows nt 4 Server
⠀• (same as above, but u can join the Ubuntu to a nt4 domain, and set Ubuntu to be the PDC, and the NT4 as BDC if you wanted)
• Windows NT 3.x (server)
⠀• (standalone only, I don't know if it can be the PDC to Ubuntu, I think it's BDC to Ubuntu only due to its age)
• previous versions of Windows NT
⠀• (I doubt you use them, and would think it's irrelevant)
Non-NT based Windows versions
• Windows Milennium Edition
⠀• (no direct domain connections, but can use logons for profiles and remote shares, but is unsecured as the logons are in the registry as plain text, as far as I know.
• Windows 98 & 98 SE
⠀• (same as Milennium Edition)
• Windows 95
⠀• (same as Milennium Edition)
• Windows 3.1.1 for Workgroups
⠀• (technically not an OS, but can link for shares only, if used with network adaptor add-ons such as Novell Netware, which would require software equivalents for Ubuntu, or Suse software)
• Windows 3.1
⠀• (same as Windows 3.1.1)
Previous non-NT-based OSs than 3.1 - (highly irrelevant to you I would assume)

A: Ubuntu can be a "Domain Controller" for Windows hosts via samba. This certainly works for XP. For newer client OSs, your samba version may have some minor limitation compared to the latest Windows server. You will easily find a tutorial online. If not, ask another question.
There are several options how an Ubuntu server can provide features similar to a Windows domain controller for Linux (including Ubuntu) clients. One option is samba if you have this infrastructure set up already. Other options are NIS or LDAP. This part of the setup happens to be more sophisticated since there are numerous options. Again, I recommend you find a tutorial suitable for your use case.
Samba can work with UNIX system accounts (regular Ubuntu accounts). Technically, the Samba password and the UNIX password are not the same thing. However, in a typically setup, changing one password automatically changes the other one, such that they always match.
Account management is always done at the server.


text:
Q: delete a document in firebase when you know the field value Context: In the frontend the user can enter of delete dates for availability. This is how I added a date:
Firestore.instance.collection('availableDates').add({
        'availableDates':date});

But I also need to delete a document from a collection in Firestore. I don't know the document id but I know the the field value which is unique. How would I go about deleting the document if I know the field value within the document. Here is a screen shot of firestore:

A: If anyone is confused after the update of why this code is not working please refer to this one. Update of March 21st, 2021.
refUser.where("city", isEqualTo: "CA").get().then((snapshot){
snapshot.docs.first.reference.delete();
});

I took a bit of time myself to get around this but if it helps even a single person stuck like me then it's all worth it. :)

A: You can fetch the document first and then delete the document. For example:
var collection = FirebaseFirestore.instance.collection('countries');
var snapshot = await collection.where('city', isEqualTo: 'CA').get();
await snapshot.docs.first.reference.delete();


text:
Q: C# Unit Test Project is missing in .NET framework v4 but present in v4.5.2 I can't seem to create a Unit Test Project (.NET Framework Project) that targets .NET Framework 4.0 (see Screenshot #1) but I can create one using .NET Framework 4.5.2 (see Screenshot #2). How do I create a Unit Test Project (.NET Framework Project) that targets .NET Framework 4.0?
Screenshot #1

Screenshot #2


text:
Q: How can I set an object in a parent class and use it in child classes? Here's some working code:
class A {
    public $Foo;

    public function GetFoo() {
        $this->Foo = 'Bar';
    }
}

class B extends A {
    function __construct() {
        $this->GetFoo();
        echo $this->Foo;
    }
}

$b = new B(); // Outputs "Bar"

Is there any way I can make this "prettier" (i.e. without the A::GetFoo() method)? I would've thought that wrapping the population of the $this->Foo inside a A::__construct() would work, but it doesn't.
Just to wrap it up, here's what I want: class A instantiates my DB object and that object is usable for every child class of A.

A: Perhaps you're overriding the parent's constructor without calling in from B?
class A {

    protected $Foo = null;

    public function __construct() {
        $this->Foo = 'Bar';
    }

}

class B extends A {

    public function __construct() {
        parent::__construct();
        echo $this->Foo;
    }

}

A: From the PHP manual:

"Class properties must be defined as
  public, private, or protected. If
  declared using var without an explicit
  visibility keyword, the property will
  be defined as public."

So, your class B can see $this->Foo.  You don't have to call GetFoo() first.  You must, however, call the parent constructor first if you need to reference $this->Foo inside of your constructor for class B.


text:
Q: Mathematical Statistics - Jun Shao, Theorem 5.10 In this theorem, Jun Shao proved some results about the asymptotic distribution for $\sqrt{n}(\hat{\theta}_p - \theta_p)$, where $\theta_p = F^{-1}(p)$ and $\hat{\theta}_p = F^{-1}_n(p)$ denote the $p$th quantile of F and the $p$th sample quantile, respectively, and $F$ is a c.d.f. from which the i.i.d. samples $X_1, \cdots, X_n$ are from.
The theorem states that

If $F$ is continuous at $\theta_p$ and there exists $F'(\theta_p+) > 0$, then $P(\sqrt{n}(\hat{\theta}_p - \theta_p) \leq t) \rightarrow \Phi(t/\sigma_F^+)$, where $\sigma_F^+ = \sqrt{p(1-p)}/F'(\theta_p+)$.

In the proof, Shao first defined $t > 0, p_{nt} = F(\theta_p + t\sigma_F^+ n^{-1/2})$, and $c_{nt} = \sqrt{n}(p_{nt} - p) / \sqrt{p_{nt}(1-p_{nt})}$, then he claimed that under the assumed conditions on $F$, $p_{nt} \rightarrow p$, and $c_{nt} \rightarrow t$.
I can understand why $p_{nt} \rightarrow p$, but my question is, why is it that $c_{nt} \rightarrow t$?
My intuition tells me to use the central limit theorem (given the form of $c_{nt})$, but I am not sure how to apply it in this case.
For reference, here's the screenshot of the complete proof of the theorem:


text:
Q: Why does this image keep reappearing? Objective-C I've set up an texture so that it spawns above the scene, and slowly scrolls down the screen for scenery. The scrolling and appearing of the texture are fine. They work how I want. The issue is that it reappears after it's left the scene even though I've set it up to be removed from the parent. This is the code:
Spawning of the item:
-(void)initalizingScrollingBackground
{
    for (int i = 0; i < 2; i++) {

        SKSpriteNode *tumbleWeed = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"tumbleWeed.png"] size:CGSizeMake(40, 40)];
        tumbleWeed.position = CGPointMake(160, -10);
        tumbleWeed.zPosition = 1.0;
        tumbleWeed.name = @"tumbleWeed";
        [bg addChild:tumbleWeed];

    }

}

Moving the item, and deleting it when it is off screen:
    -(void)moveItems {

    [self enumerateChildNodesWithName:@"tumbleWeed" usingBlock:^(SKNode *node, BOOL *stop) {
        SKSpriteNode * tumbleWeed = (SKSpriteNode *)node;
        CGPoint bgVelocity = CGPointMake(0, -BG_VELOCITY);
        CGPoint amtToMove = CGPointMultiplyScalar(bgVelocity,_dt);
        tumbleWeed = CGPointAdd(amtToMove, tumbleWeed.position);

        if (tumbleWeed.position.y > self.size.height + 10) {
            [tumbleWeed removeFromParent];
        }

    }];

}

I don't understand why the item reappears at the top of the scene and restarts the scrolling? Any reasons why? How can I fix it?
Thanks.

A: Two ideas for you:
1) Put a breakpoint in -(void)initalizingScrollingBackground so that the app will pause there. Then look at the call stack to see how the call to this method is being triggered.
2) Instead of calling removeFromParent on the child object, try starting that action from the parent. Ex: [bg removeChild: tumbleWeed]; I've seen occasions in other projects where making this call from the child can be problematic, and so I've adopted the practice of always  having the add/remove action start with the parent.
Good luck! Hope this helps....


text:
Q: Unable to launch/debug ASP.NET Web Site after upgrading to Visual Studio 2013 I've just installed Visual Studio (Ultimate) on my development machine. The install seemed to go fine, but when I try to run a VS2012 ASP.NET Web Application project, IE launches and gives me:

IIS Express is installed, and the project is set to use IIS Express:

IIS Express is running, the port is open etc, but it doesn't appear to be serving any webpages. If I look in the IIS Express logs, I can see the requests being returned with what looks like a 303 error:
2013-12-23 14:22:49 ::1 GET /login.aspx - 25869 - ::1 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+WOW64;+Trident/5.0) - 303 0 0 0
2013-12-23 14:22:53 ::1 GET /login.aspx - 25869 - ::1 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+WOW64;+Trident/5.0) - 303 0 0 0

Any ideas what I need to do/undo to get VS2013 running my project?

A: Cracked it. My 'web.config' file had the following rewrite rule:
<rewrite>
  <rules>
    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$"/>
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/>
    </rule>
  </rules>
</rewrite>

... which would force HTTPS on the live site. This didn't cause a problem when using VS2012's Cassini development web server, but as that's now been replaced it seems that IIS Express is trying to enact the rewrite rule. I'm not sure if the URL Rewrite module is available or compatible with IIS Express, but I can easily comment out the offending lines for now and leave them in place on the live site.

A: Check you web config and see if you have this
<authentication mode="Forms">
  <forms loginUrl="~/login.aspx" />
</authentication>

I have had a redirect problem when I installed 2013 and it was centered on the forms loginUrl


text:
Q: Where to execute code that comes after retry in rxjs Angular 7 I'm working on an HTTP interceptor & I want to Logout my user if the refreshToken API fails after the retries.
    return this.authService.refreshToken().pipe(
      switchMap((token: any) => {
        console.log(token);
        this.isRefreshing = false;
        this.refreshTokenSubject.next(token.accessToken);
        return next.handle(this.addToken(req, token.accessToken));
      }),
      retry(3), //Tries the refreshToken() API if it returns with an error.
      catchError(error => {
      //If the refreshToken() API never returns a successful response, I want to Logout.
        this.authService.Logout();
        return throwError(error);
      }
    );

My question is, am I doing the catchError correctly? I only want it to happen after it retries 3 times and still fails, but I'm worried that it will catchError before retrying.

A: Yes, it should work only after retry. Also, you can put it not to catchError but to subscribe error callback.
Here is an simulation of your use-case: https://stackblitz.com/edit/typescript-kbfkq7
First subscription fails several times but is below retry point - so it resolves.
Another one is above - so catchError and error callback are emitted.


text:
Q: Why can't I get location using CID, LAC, MCC and MNC? I get CID, MNC, MCC, LAC from this code
telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
cid = cellLocation.getCid();
lac = cellLocation.getLac();

and I put it in here http://opencellid.org/cell/get?key=???&mcc=520&mnc=18&lac=24511&cellid=282399 and I get back error anyone can tell me what should I do?
Are there other ways to get Lat Lon Using CID, MNC, MCC, LAC on android?

A: I´m Markus, the maintainer of OpenCellID.
I guess that worldwide more than 50.000.000 base stations exist.
OpenCellID currently has 5.5 million base stations in its database.
I checked the database and found out, that the cell you are looking for is not (yet) in the OpenCellID database.
The best way to overcome this chicken-and-egg problem is if apps contribute to OpenCellID and use OpenCellID data at the same time.
OpenCellID has recently published an Android library which makes contribution to OpenCellID as well as using the OpenCellID data as easy as possible. You can find more information here: http://wiki.opencellid.org/wiki/Android_library
Please note that publishing the secret personal OpenCellID apiKey on the web is not recommended. Therefore I have deleted it now.


text:
Q: Declare scalar variable c# When I execute my code I have this error :

The scalar variable "@qte" must be declared.

        Connection newconnection = new Connection();
        newconnection.Connection_Today();

        SqlCommand comm = new SqlCommand();
        comm.Connection = Connection.conn;

        comm.CommandText = "UPDATE F_DOCLIGNE SET DO_DateLivr = @date, DL_Qte = @qte, DL_Remise01REM_Valeur = @remise, DL_PrixUnitaire = @pu, DL_MontantHT = (@pu - ((@remise * @pu) / 100)) * @qte where AR_Ref = @code";

        SqlParameter param = new SqlParameter("qte", SqlDbType.Int);
        SqlParameter param1 = new SqlParameter("remise", SqlDbType.Int);

        comm.Parameters.AddWithValue("@date", textBox_livr.Text);
        comm.Parameters.Add("@pu", SqlDbType.Int).Value = textBox_prix.Text;
        comm.Parameters.Add("@code", SqlDbType.VarChar).Value = textBox_art.Text;

        comm.ExecuteNonQuery();

When I try comm.Parameters.AddWithValue("@qte", DL_Qte) I have the error

The name 'DL_Qte' don't exist in the current context

My variables @qte and @remise have the value of the fields in my database and they are used to calculate an amount.
How can i declare scalar variables without doing procedures?

A: You created an instance of the parameter "@qte" (Variable "param") with
SqlParameter param = new SqlParameter("qte", SqlDbType.Int);

but didn't add this "param" with comm.Parameters.Add, so that's why this parameter is missing.
so you should do:
comm.Parameters.Add(param);

A: If, for instance, @qte is a value that already comes from the database, its not a variable. You use variables to send values from your code to the db. In your case (if i understood right) you need to rewrite the update statement:
UPDATE tablename SET column = (select 1) where otherecolum = @var

Where offcourse, you have to provide the 'select 1' implementation to query the correct value.

A: If, as you imply in your question, you want to use the values of the DL_Qte & DL_Remise01REM_Valeur fields, rather than update them - you can use them directly if they are in the same row you are updating :
comm.CommandText = @"UPDATE F_DOCLIGNE SET DO_DateLivr = @date, DL_PrixUnitaire = @pu,
        DL_MontantHT = (@pu - ((DL_Remise01REM_Valeur * @pu) / 100)) * DL_Qte
        where AR_Ref = @code";


text:
Q: Is order by clause allowed in a subquery Is there any reason why or why not you should do an 'order by' in a subquery?

A: Unless you use top it is not useful since you will be ordering in the outer query anyway

A: Smarter people say that is not proper/valid way to do it.
In my case SELECT TOP 100 PERCENT in sub-query solved the problem.
Cheers

A: Yes: It should not be done, because it does not make sense conceptually.
The subquery will be used in some outer query (otherwise it would be pointless), and that outer query will have to do ordering anyway, so there's no point ordering the subquery.
This is because query results in SQL will come in no particular order, unless you use an explicit ORDER. So even if you used ORDER in the subquery, you have no guarantee that this will affect the order of the results from the outer query; so it's pointless.
It may of course make a difference in some specific RDBMS because of its implementation, but that will be implementation-specific, and not something you should rely on.
Edit: Of course, if you use TOP or LIMIT in the subquery, you will need to use ORDER. But that's not standard SQL anyway...

A: You should use it if the subquery uses some kind of LIMIT / TOP.
SQL Server will not allow it unless the subquery contains TOP or FOR XML clause as well:
-- Fails
WITH    q(id) AS
        (
        SELECT  1
        UNION ALL
        SELECT  2
        )
SELECT  *
FROM    (
        SELECT  *
        FROM    q
        ORDER BY
                id DESC
        ) q2

-- Succeeds
WITH    q(id) AS
        (
        SELECT  1
        UNION ALL
        SELECT  2
        )
SELECT  *
FROM    (
        SELECT  TOP 1 *
        FROM    q
        ORDER BY
                id DESC
        ) q2

-- Succeeds, but ORDER BY is ignored
WITH    q(id) AS
        (
        SELECT  1
        UNION ALL
        SELECT  2
        )
SELECT  *
FROM    (
        SELECT  TOP 100 PERCENT *
        FROM    q
        ORDER BY
                id DESC
        ) q2

A: You can do it, but I wouldn't usually unless you have a need.
The optimiser will ignore it (or throw an error?)
See "Intermediate materialisation" for some usages.

A: Depending on the size of the sub-query, it will impact performance to a varrying degree.
Order shouldn't matter on a sub-query though. You should be able to move the Order By portion to the Outer Query (which should be the one returning the final results).

A: No ORDER BY is valid in a subquery when you are interested in a subset of the overall data, hence you always need a TOP (SQL Server). There's no point having an ORDER BY without TOP in a subquery because the overall ordering of the results is handled by the outer query.

A: You should not use it.  According to the 'Art of SQL', this actually prevents the optimizer from performing various optimizations that it could otherwise do because this pre-maturely transforms the data.

A: It's totally legit. I.e. SELECT id FROM entries WHERE author_id IN (SELECT id FROM authors ORDER BY name DESC) but you'll really get the same results usually.


text:
Q: Redirect Visual Studio to new TFS Location We have migrated TFS from one server to another. I have verified that the source files and history do exist in the new server location.
How do I now redirect Visual Studio to look at the new server location? I would like to not lose any of the files, history and to realize pending changes, etc.
TIA

A: You have to connect to the new TFS from Team, Connect to Team Foundation Server menu.


text:
Q: How to read a file line by line, then print the line if it contains a string with a range of value in Python? I'm a newbie with Python 2.7 and I'm still trying to get the hang of it.
I have a text file with a row of lines that contain strings like this:
"AA,,BB,2014-02-06,0,0|CC,,DD,2014-02-27,0,0|EE,,FF,2014-02-04,1,1"#"GG"#"USD"#"true"#Total : USD#1638.93#

(There's a bunch of text before 'USD' that varies with each line.)
I tried doing this:
with open('out_put_usjfk50.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:
        amount = float(row[5])
        if amount <= 800:
            print row
        elif amount is None:
            pass

but I got the same error: ValueError: could not convert string to float:
I'm stumped. How do I go through each line to check for the integer value (that's part of a string), and then print the line(s) if it's less than, say, USD1500? I'd appreciate it if someone can point me to the right direction!

A: You have a CSV file; use the csv module:
import csv

with open('filename.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:

New each row object is a list of strings; each string representing a column in your file.
Say the '1638.93' column is column 8, then you'd use (with Python using 0-based indexing):
amount = float(row[7])

Now you have a floating point number from that string, and you can test against it:
with open('filename.csv', 'rb') as f:
    reader = csv.reader(f, delimiter='#')
    for row in reader:
        amount = float(row[7])
        if amount <= 1500:
            print row


text:
Q: Express app not working on local network without internet I have an express app with which I want other computers in the same WIFI Network to connect to it but without the internet being available.
The main PC which is hosting the app has the following fixed IP: 192.168.1.60
And I have done the following code in my server.js
app.listen(5000, '192.168.1.60' () => {
  console.log(`Server launched with port 5000`);
});

So whenever I try to access the app from another machine, it does not load unless I have internet.
Is there a way to make it work without the internet?

A: app.get('/', (req, res) => {
  res.send('Hello User!')
})
app.listen(5000, () => {
  console.log(`Server launched with port ${port}`)
})

Make sure you enter following URL http://192.168.1.60:5000 in your browser


text:
Q: Java FutureTask completion check I have checked Oracle Java API, which gives some info that FutureTask.isDone()
but I need to check whether the task has completed or terminated with any error.
isDone() method will return even if it completes/terminates. But I need to know whether it's completed or terminated due to some problem.

A: If the FutureTask is done, call get() afterwards (can be without any timeout, it should return immediately). It will either return some result or throw:

ExecutionException - if the computation threw an exception

ExecutionException.getCause() will return the exception thrown from your task.

A: Why not call FutureTask.get() ?
This will return the result or throw an exception containing the exception originally thrown/caught. If the task hasn't complete dit will block, and you have the option to provide a timeout.
I would normally expect clients simply to call get() on each FutureTask in turn once created, rather than poll isDone().

A: When isDone() return true you would like to get result by calling get() method to check the result of execution. get() operation can throw ExecutionException, which consist of cause, where you can find a problem.


text:
Q: Gestionando con Git un proyecto que se encuentra entre dos carpetas He creado dos carpetas, A y B que en principio tienen que ver con proyectos diferentes, A y B pero yo quiero juntarlos, porque para mí son el mismo proyecto, porque comparten muchos archivos y porque están relacionados con lo mismo, un tutorial de Angular que estoy siguiendo. Estaba trabajando con la carpeta A, hice un commit y después me fui a la carpeta B, hice un git init y empecé a comitear los cambios, el problema lo tengo cuando voy a hacer un git pull:
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=GuillermoBaldan/<branch> master

La verdad es que no entiendo muy bien lo que está pasando. Si alguien me lo puede explicar...


text:
Q: Substract 10 years from time variable in netCDF-file I need to substract 10 years from the time variable (dimension) in a netCDF-file.
The original input file starts at 1969-06-20 00:00 and ends at 1971-07-01 00:00, with 3H time steps. The time unit in the original file is unix seconds since 1970-01-01, indicated as datetime64[ns] format in Python. I want to substract 10 years from every timestep so that the new file starts with 1959-06-20 00:00 and end at 1961-07-01 00:00.
I am loading the netCDF-file in Python with xarray and substracting 10 years by using np.timedelta64.
Then I  convert and save the modified dataset as a new netCDF-file, see my code below.
import xarray as xr
import numpy as np

# load original file
ds = xr.open_dataset('original_file.nc')
ds = ds.load()

# substract 10 years from time dimension
ds['time'] = ds.time - np.timedelta64(3652, 'D')

# save modified dataset as new nc-file
ds.to_netcdf('new_file.nc')

I am experiencing two problems.
Firstly, since my file contains a leap year (1960) it is not sufficient to use 365.242 days/yr * 10 yrs = 3652 day, as a result the output is one day off and starts at 1959-06-21 00:00. But I get the following error message what I try to usenp.timedelta64 with the years 'Y' option:
UFuncTypeError: Cannot cast ufunc 'subtract' input 1 from dtype('<m8[Y]') to dtype('<m8[ns]') with casting rule 'same_kind'

Secondly, in the operation the time unit changes from unix seconds since 1970-01-01 for the original input netCDF-file to hours since [start date], which in my case becomes 1959-06-21 00:00, for the created output netCDF-file. I want the time unit to still be in seconds since 1970-01-01.
Does anyone have a suggestions or input to how I can solve this issue?
Thanks everyone

A: For the main part of your question, you should convert the time coordinate to an index before performing the arithmetic and use Pandas.Timedelta
ds['time'] = ds.time.to_index() - pd.Timedelta(days=3652)

This should work for most datetime-like indexes in Xarray.
Finally, I suggest reading this section in the Xarray docs that describes how to control the encoding of time variables.


text:
Q: How to Order data which have + and - value I have some data in one field like this.
Name:   Rate
A :      +1.05
B :      +1.95
C :      +0.50
D :      -1.25
E :      -0.35
F :      -1.50
But When order by rate DESC
I am getting like this.
Name:   Rate
B  :     +1.95
A  :     +1.05
C  :     +0.50
D  :     -1.25
E  :     -0.35
F  :     -1.50
But It should be or I want to like this
Name:   Rate
B  :     +1.95
A  :     +1.05
C  :     +0.50
E  :     -0.35
D  :     -1.25
F  :     -1.50
Please help

A: I think best solution is adding new column which is store plus or minus flag, then you can do it easliy, if minus order it ascending else order it descending
select * from tablename where type='+' order by value desc
union
select * from tablename where type='-' order by value asc

something like that


text:
Q: Multi image's resolution development with iOS I am a beginner in iOS development, and I want to develop a universal iOS app (IPhone3 & 4 & 5, iPade 1 & 2 & 3 & 4, iPad Mini).
After several researches on Internet, I found the following results:

My questions are:
1- Are my results true?
2- Do I need the three image's resolution(because we have 3 aspect ratio) to developp one app for the different iOS devices?
Thanks

A: 1
Yes, Its true. You can find more details from Icon and Image Sizes porvided by Apple.
2
Yes, Mainly we required these three type of Images also depends on your iOS project.
Icon and Image Sizes,
App Icon and
Launch Images.
And also please review this iOS Resolution Quick Reference.
And as per you comment you can find the Icon resolution information for android from Android Developer portal. And for window you can find from Window Developer portal (Differ for window phone 7 and window phone 8). or for you more information when we create a project for Window Phone this will give you sample images you can replace according to there and you requirements.


text:
Q: iText flying-saucer how to change background on last page I have a specific document. Background first and last page is different from the other pages of the document.
According to the question answered here:
Flying Saucer hide header and footer on first page
The first page I defined using the trick @page :first:
@page{
    background-image: url('... my regular background ...');
}
@page :first {
    background-image: url('... first page background ... ');
}

How to change the background on the last page?

A: If you know in advance what will be displayed on the last page, you can use CSS3 named pages.
Here is a simple example:

Footer page 1 and 2

Footer for last page

Page 1 content

Page 2 content

Page 3 content


text:
Q: Can't return focus to the main window after showing dialog I create dialog window in MFC using CWnd::DoModal function.
The window is instantiated in CWinApp::OnIdle()
CPatientFile pf;
pf.DoModal();

When the DoModal function returns the focus is not returned to the main window.
I tried to set focus manually
AfxGetMainWnd()->SetFocus();

Also tried to set the main window as foreground or active.
Generally I have touch screen, so when I close the Dialog I need to press the button on the main window to get it work.
So what is the right way to do it?

A: Just check the constructor of CPatientFile. It may be accepting the parent window CWnd *. Pass the main window as the parent.
Like
CPatientFile pf(this); //if this code is in main window class itelf

or
CPatientFile pf(AfxGetMainWnd());

Updated:
If you have instantiated the dialog from the main window, then the focus will automatically go back to the window when the dialog is closed. I am suspecting that you have instantiated the dialog from the app class itself (CWinApp) after creating the main window. If this is the case then the main window may not get the focus & you must create the dialog from within the main window. Or if you are creating the dialog in a separate thread.
As a work around you can use AfxGetMainWnd()->SetForegroundWindow() or AfxGetMainWnd()->SetActiveWindow(). But first I would try to find the cause of the issue & try to write better code (like suggested in above paragraph).

A: If you have copy-pasted, the statement is itself incorrect:
CPatientFile pf();

The next line shouldn't compile at all. Why? Because it is declaring a function named pf which returns CPatientFile.
If that is correct, may I ask if there is any multithreading involved. Is another thread creating a window?
How do you check if parent windows has (not) got the focus?


text:
Q: How to convert a regular grammar to finite automaton? How does one convert a regular grammar into a finite automaton (FA)? For instance, what would a finite automaton corresponding to the following regular grammar look like?
VN = {S, B, D} (nonterminals)
VT = {a, b, c} (terminals)
 P = {S -> aB, S -> bB, B -> bD, D -> b, D -> aD, B -> cB, B -> aS} (productions)

A: The good news is that this is not too hard. The idea is that each of the nonterminals will become a state in a nondeterministic finite automaton accepting the language of the grammar, and productions will become transitions. Our NFA will have states S, B and D, and will transition among those states according to the production rules. Our NFA looks like this:
       ___a__      _a_
      /      \    /   \
      |      |    \   /
      V      |     \ /
----->S-a,b->B--b-->D
            / \
           /   \
           \_c_/

There was one dangling production D -> b which we haven't added yet. We need to introduce another state, not corresponding to an nonterminal symbol, to allow us to transition from D on b and accept some strings:
       ___a__      _a_
      /      \    /   \
      |      |    \   /
      V      |     \ /
----->S-a,b->B--b-->D--b-->Q
            / \
           /   \
           \_c_/

Now if we make S the initial state and Q the accepting state, we have an NFA that works. If we want a DFA, we might notice that this FA is only nondeterministic because we are lacking required transitions from states S, D and Q. We can add the missing transitions by introducing a new dead state X which will keep track of the NFA we just derived having crashed at some point during its processing:
       ___a__      _a_
      /      \    /   \
      |      |    \   /
      V      |     \ /
----->S-a,b->B--b-->D--b-->Q
      |     / \     |      |
      |    /   \    |      |    a,b,c
      c    \_c_/    c    a,b,c  /   \
      |             |      |    \   /
      V             V      V     \ /
      +-------------+------+----->X


text:
Q: How to create a JavaFX TableView without warnings? I'm following a tutorial by Oracle to create a TableView in JavaFX. In this screenshot, I've copied and pasted the code and I get several errors, which aren't mentioned in the tutorial anywhere.

The warning on the TableView says:

TableView is a raw type. References to generic type TableView<S>
   should be parameterized

the warning on the TableColumn says:

TableColumn is a raw type. References to generic type TableColumn<S,T>
  should be parameterized

and the warning on the addAll method says:

Type safety: The method addAll(Object...) belongs to the raw type
  ObservableList. References to generic type ObservableList<E> should be
  parameterized

I looked at the documentation and saw that they do require parameters (which is confusing because the tutorial didn't mention this) but I don't understand what they are supposed to be. If I do
TableView<String> table = new TableView<>();

and
TableColumn<String, String> tableCol = new TableColumn<>(...);

I still get a warning on the addAll method, which says:

Type safety: A generic array of TableColumn<String,?> is created for a varargs parameter

I really can't understand what is expected for the type parameters. I know I can suppress the warnings, but that seems like bad practice. What am I supposed to do instead?

A: TableView requires data objects that it will try to represent in each row.
So as per your example, you are trying to display a list of Persons in your table. So your tableView reference type will be of type Person. like
TableView<Person> tableView = new TableView<>();

And now each column represents the data type of the information you want to display. In your case all are Strings. But it can be varied as per the data that you want to show.
Consider for example the below Person object.
public class Person{
     private StringProperty firstName = new SimpleStringProperty();
     private StringProperty lastName = new SimpleStringProperty();
     private IntegerProperty age = new SimpleIntegerProperty();
     private DoubleProperty weight = new SimpleDoubleProperty();
}

In the above person object if you want to represent the data in each column your column declarations will be like..
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
TableColumn<Person, Integer> ageCol = new TableColumn<>("Age");
TableColumn<Person, Double> weightCol = new TableColumn<>("Weight");


text:
Q: Use Mouse without Borders between two PCs in different networks I'm trying to find a solution similar to Mouse without Borders that works no matter what network the computers are connected to.
I need this because my Wi-Fi network is separate than my wired network.
For example, say Computer A is connected to Network A. Computer B is connected to Network B. Now connect the two computers. Is it possible?

A: Assuming that the wirless network is based within the wired network, you actually can use MWB version 2.1.2.1212 (available here!) to do this. You probably could with an earlier version as well, but this is the first one I'm sure that it works properly on.
The "secret sauce" is as follows...

*

*Of course make sure that you are using the same exact Security Key on each machine. Don't forget that this is case sensitive.

*Make sure the TCP box on the "Machine Setup" tab of the dialog is checked.

*Take note of the adapter that you want to use (it's in the drop down list next to the TCP box) because you'll need to know the IP address of each machine to control/be controlled.

*On the "controlling machine" (which is a misnomer because they're all really controlling machines) go to the "IP Mappings" tab and enter both the following (without the braces):
{computer name}{space}{IP Address}
So for a machine to be controlled named "SCAR" with an IP of 192.168.4.444 it would be:
SCAR 192.168.4.444

*Now go back to the "Machine Setup" tab on the controlling machine and click "Apply".

*On the machine "to be controlled" (and assuming the controlling machine is "MUSTAFA 192.168.3.333") it would be:
MUSTAFA 192.168.3.333

*Now go back to the "Machine Setup" tab on the machine to be controlled and click "Apply".
When you see...
Connected -->
<-- Connected
... on the dialog of for each entry on both machines you're good to go.
What's described above works our internal networks which are on 10.www.xxx.yyy and 10.aaa.bbb.ccc, respectively. And yes, those octets use different letters because they represent completely different octects.
The only thing that I haven't gotten to work yet (and won't spend too much time to figure out right now) is how to get a machine connected to a router with one of those 10.www.xxx.yyy IPs but has its own DHCP server to be controlled by a machine on the 10.aaa.bbb.ccc side. With my limited networking knowledge I don't think this is going to be possible.
IHTH!

A:
On the "controlling machine" (which is a misnomer because they're all really controlling machines) go to the "IP Mappings" tab and enter both the following (without the braces):
{computer name}{space}{IP Address}

this worked for me, for some reason i had to use a DNS name rather than an IP address.


text:
Q: Does truncating anchor text hurt SEO? Does truncating the anchor text in a link affect SEO negatively? Google is only seeing part of the relevant text in the anchor. I have a long list of product urls that I need to link to from my homepage. Vast majority of those links are under 30 characters but some are really long, over 100 characters. For UI/UX reasons I have been given a character cap on these anchors so I have to find the best solution for the anchor text I use given that restriction. I'm very interested in the SEO perspective people can give.
Example Anchor Text:
NormalPartNameNumberTruncated
VeryVeryLongWhichIsPartNumberTruncated...
AnotherVeryVeryLongPartNumberWhichIsTruncated...
NeedToLimitMyVeryLongPartNumberAnchors...
Questions:
Should I use ellipsis at the end of truncated anchors text or leave as many chars as possible?
Does Google look negatively at truncating really long anchors?
Thanks in advance for thoughts and insights!

A: The only affect truncating will have is any text removed from the anchor text won't be considered when Google determines the value of that link for the receiving page. So if these are internal links you will be reducing the value of those links. But if the text is really long otherwise, it's a tomato/tomato scenario as you can be sure Google limits the amount of keywords it considers in links as spammers are sure to cram spammy links full of text.
Bottom line, if the text you are truncating is very long, this won't hurt you. If it helps your users, then it is worth doing.

A: How about leaving the entire text there and using text-overflow: ellipsis?  See http://www.quirksmode.org/css/textoverflow.html
(That's subject to figuring out whether old browsers that don't support text-overflow: ellipsis are important to you, and whether there's a workaround.)


text:
Q: Error: This action with HTTP GET is not supported by NextAuth.js Unable to authenticate my Next.js app with credentials.
Error: This action with HTTP GET is not supported by NextAuth.js
As far as I know everything is correct according to the doc. and it was working too. it suddenly start returning this error.
package.json
{
  "name": "materio-mui-react-nextjs-admin-template-free",
  "description": "Most Powerful & Comprehensive Free MUI React NextJS Admin Dashboard Template built for developers! ",
  "license": "MIT",
  "version": "1.0.0",
  "author": {
    "name": "IWorkplc",
    "url": "https://iworkplc.com/"
  },
  "bugs": {
    "url": "https://github.com/themeselection/materio-mui-react-nextjs-admin-template-free/issues"
  },
  "private": false,
  "repository": {
    "type": "git",
    "url": "https://github.com/themeselection/materio-mui-react-nextjs-admin-template-free.git"
  },
  "homepage": "https://themeselection.com/products/materio-free-mui-react-nextjs-admin-template/",
  "keywords": [
    "react",
    "javascript",
  ],
  "scripts": {
    "info": "next info",
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "export": "next export",
    "lint": "eslint --fix \"src/**/*.{js,jsx}\"",
    "format": "prettier --write \"src/**/*.{js,jsx}\"",
    "postinstall": "patch-package"
  },
  "dependencies": {
    "@emotion/cache": "^11.6.0",
    "@emotion/react": "^11.7.0",
    "@emotion/server": "^11.4.0",
    "@emotion/styled": "^11.6.0",
    "@iconify/react": "^4.0.0",
    "@material-ui/icons": "^4.11.3",
    "@mui/icons-material": "^5.10.15",
    "@mui/lab": "^5.0.0-alpha.70",
    "@mui/material": "^5.4.3",
    "@popperjs/core": "^2.11.2",
    "@react-oauth/google": "^0.5.0",
    "@reduxjs/toolkit": "^1.9.0",
    "apexcharts-clevision": "3.28.5",
    "axios": "^1.2.0",
    "apisauce": "^2.1.6",
    "babel-eslint": "^10.1.0",
    "clsx": "^1.1.1",
    "formik": "^2.2.9",
    "mdi-material-ui": "^7.1.0",
    "moment": "^2.29.4",
    "next": "12.3.1",
    "next-auth": "^4.14.0",
    "nprogress": "^0.2.0",
    "react": "17.0.2",
    "react-apexcharts": "^1.3.9",
    "react-datepicker": "^4.5.0",
    "react-dom": "17.0.2",
    "react-perfect-scrollbar": "^1.5.8",
    "react-popper": "^2.2.5",
    "react-redux": "^8.0.5",
    "react-toastify": "^9.1.1",
    "react-use-websocket": "^4.2.0",
    "redux-logger": "^3.0.6",
    "socket.io-client": "^4.5.4",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "eslint": "^7.32.0",
    "eslint-config-next": "12.0.4",
    "eslint-config-prettier": "^8.3.0",
    "eslint-import-resolver-alias": "^1.1.2",
    "eslint-import-resolver-typescript": "^2.5.0",
    "eslint-plugin-import": "^2.25.4",
    "next-transpile-modules": "^9.0.0",
    "patch-package": "^6.5.0",
    "postinstall-postinstall": "^2.1.0",
    "prettier": "2.5.1"
  }
}

pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import { getToken } from 'next-auth/jwt'

export const authOptions = {
  // Configure one or more authentication providers
  // debug: true,
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          scope:
            'openid email profile https://www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/gmail.modify'
        }
      },
      idToken: true
    }),
    {
      clientId: process.env.QUICK_BOOKS_CLIENT_ID,
      clientSecret: process.env.QUICK_BOOKS_CLIENT_SECRET,
      id: 'quickbooks',
      name: 'QuickBooks',
      type: 'oauth',
      wellKnown: 'https://developer.api.intuit.com/.well-known/openid_sandbox_configuration',
      authorization: { params: { scope: 'com.intuit.quickbooks.accounting openid profile email phone address' } },
      userinfo: {
        async request(context) {
          return await context.client.userinfo(context.tokens.access_token)
        }
      },

      idToken: true,
      checks: ['pkce', 'state'],
      profile(profile) {
        return {
          id: profile.sub,
          name: profile.name,
          email: profile.email,
          image: profile.picture
        }
      }
    },
    // ...add more providers here
    {
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      id: 'googledrive',
      name: 'Google Drive',
      type: 'oauth',
      wellKnown: 'https://accounts.google.com/.well-known/openid-configuration',
      authorization: {
        params: {
          scope:
            'openid email profile https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.resource'
        }
      },
      idToken: true,
      checks: ['pkce', 'state'],

      profile(profile) {
        return {
          id: profile.sub,
          name: profile.name,
          email: profile.email,
          image: profile.picture
        }
      }
    }
  ],
  callbacks: {
    async session({ session, token, user }) {
      session.user.id = token?.id
      session.accessToken = token?.accessToken
      session.provider = token?.account?.provider
      return session
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      if (user) {
        token.user = user
      }
      if (account) {
        token.account = account
      }
      return token
    }
  }
}

export default NextAuth(authOptions)

i tried by upgrading both next and next-auth packages but it didn't work.
[...nextauth].js is inside pages/api/auth


text:
Q: How to install and configure NTP Server on vSphere? I need to install and configure NTP service on VMware vSphere
, Need help for the same.
I tried many solutions but none of them worked.

A: This can be done with following Steps:

*

*Configure NTP servers on ESXI Server (physical host).

*Synchronize virtual machines with Server.


text:
Q: How to run javascript function from aspx page? I have written some code there are 27 different functions that execute like this..
    ElseIf websiteID = 15 Then
                    parserTravelPost(hotelURL, hotelID, websiteID)
                    nextPageLink = ""
                ElseIf websiteID = 16 Then
                    parserTripAdviosr(hotelURL, hotelID, websiteID)
                    nextPageLink = ""
                ElseIf websiteID = 17 Then
                    parserTripTake(hotelURL, hotelID, websiteID)
                    nextPageLink = ""
                ElseIf websiteID = 18 Then ........

After every function i want a literal or any other way to tell the function is finished...
example after the first function finish , the literal should shows example finished now starting function 2 ...
Any help/tips/code?
Thank you

A: you can simplay response.write the javascript code or you can use registerclicentscriptBlock in asp.net
//vb version
Dim scriptText As String
    scriptText = "return confirm('Do you want to submit the page?')"
    ClientScript.RegisterOnSubmitStatement(Me.GetType(), _
        "ConfirmSubmit", scriptText)

hope it helps.


text:
Q: How do I get to the Chrome address bar with a keyboard shortcut? I used to be able to use F6 to get to the address bar (omnibox) on Chrome. Maybe it's platform dependent, as I'm on a Mac. But I'd like to know if there's a different keyboard shortcut I can use or a setting I can configure to achieve the same functionality.

A: The keyboard shortcut for jumping to the address bar is ⌘+L, https://support.google.com/chrome/answer/157179?hl=en-GB


text:
Q: How to hide type inheritance in .NET XML web services WSDL I have a web service, it exposes method M(B). Here B: A (B inherits from A).
I need to hide this inheritance from the service consumers. The consumers don't need to know about A, although B will have its properties.
I know that I can write my own WSDL, but is there a way to make .NET do what I want automatically?

A: This is answered well at question:

How to hide an inherited property in a class without modifying the inherited class (base class)?

In short, you can override the properties and methods so that they just throw an exception, and "decorate" the overridden versions, marking them as obsolete. But the best practice would be to write a separate class for a web service contract.


text:
Q: Pass struct by value Given the following code, I'm curious to know how to avoid the following exception
System.InvalidOperationException was unhandled
Message=Collection was modified; enumeration operation may not execute.
Source=mscorlib
StackTrace:
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Collections.Generic.List`1.Enumerator.MoveNext()
   at PBV.Program.Main(String[] args) in C:\Documents and Settings\tmohojft\Local Settings\Application Data\Temporary Projects\PBV\Program.cs:line 39
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException:

CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PBV
{
class Program
{
    struct structItem
    {
        public int y { get; set; }
        public int z { get; set; }
    }

    struct testStruct
    {
        public int x { get; set; }
        public List<structItem> items { get; set; }
    }

    static void Main(string[] args)
    {
        testStruct a = new testStruct();
        structItem b = new structItem();

        for (byte i = 0; i <= 10; i++) {
            b.y = i;
            b.z = i * 2;
            a.items = new List<structItem>();
            a.items.Add(b);
        }

        testStruct c = new testStruct();
        c = a;

        int counter = 0;

        //exception thrown on line below
        foreach (var item in a.items) {
            structItem d = item;
            d.z = 3;

            c.items[counter] = d;
            counter++;
        }

        a = c;
    }
}
}

I originally tried to simply put the following in the second foreach:
item.z = 3;

But that caused the following error:
Cannot modify members of "item" because it is a "foreach iteration"

I tried to create a temporary object in order to be able to modify the struct data inside the foreach, but I recieve the exception above. My best guess is because my temporary struct is saving a reference to the original struct rather than the value itself - which is leading my original struct to be updated when my temporary struct is.
So my question is:
How do I pass this struct by value rather than reference? Or is there an entirely different way to get around this issue?
Thanks in advance for the help.
EDIT: Thanks for all the answers guys. I'm aware that the list is a reference type, but does that make it impossible to pass by value instead of reference then?

A: I'm a little confused by what your example code is trying to do, but I think perhaps part of your confusion may be that when you set c = a, you expect it to make a copy of the list.  It does not.  While the structure itself is a value type, the items property it contains is not.  List<> is a reference type, so when you set c = a, it copies that items reference to c.  So, when you enter the loop, both a and c contain a reference to the same list object.  Therefore, when you modify the list while you are enumerating through it, it will always fail.
A simple way to avoid this is to iterate through a static copy of your list:
foreach (var item in a.items.ToArray())

A: a.Items and c.Items are still the very same List instance. You could just iterate over it with an old-fashioned for loop instead. That way you're not using any enumerator and thus can modify the list as you want.
for (int i = 0; i < a.Items.Count; i++)
{
    c.Items[i] = whatever;
}

You're keeping a counter anyway, so this seems like the natural way to do it. For performance reasons you might want to store the list size in a local variable if you don't intend to add or remove any items from it.

A: Mutable value object (struct) are much harder to deal with than immutable. Consider making the struct immutable and redesigning your code around it.
It is often easier to not use struct at all unless you know exactly where benefits and pain points are. Try switching your code to class instead and measure if performance meets your goals.
Note: c = a; is shallow copy (which is not really making second copy of your testStruct at all, but refers to a), it looks like you want deep copy - consider making it constructor instead and copy array instead of referencing it.

A: In some applications, mutable value types offer the most appropriate semantics.  The inherent meaning of a List<someValueType> is often much clearer than that of a List<someMutableClassType>(), regardless of whether or not the value type supports any method of mutation other than all-field-copy(*).  Unfortunately, the built-in collections like List<T> really do not support mutable value types very well, since they do not expose any means of mutating the stored items other than all-field-copy.
I would suggest that in many cases, you may be best off not using List<T> but instead simply keeping a T[] and an item count.  If you want to add an item to the collection, check to see whether the count is greater than or equal to the length; if so, double the length.  Then store the new item in the slot indicated by the count and increment the count.
If you really want to use a List<someStructType>, you can use the approach suggested by others, iteratating through items to be modified by using an integer loop on the index, rather than using a foreach.  When working with mutable structs, however, the ability to say myArray[i].X = i+4; instead of var temp=myList[i]; temp.X = i+4; myList[i] = temp; is worth the slight hassle of dealing with array expansion.
(*) The semantic meaning of a List<MutableClassType> can vary, depending upon whether each list item holds the only reference to a distinct object instance, or whether instances holding the same data may be shared.  No such ambiguity exists with a List<StructNotContainingMutableClassReferences>.
(**) If X and Y are storage locations of the same struct type S, the statement X = Y will copy all public and private fields from Y to X, in some arbitrary order.  The statement X = new S(params); creates a new instance of struct type S with all fields blank, calls the constructor on it, and then copies all of the fields from that new instance to X.  Consequently, if any fields a value-type instance can ever hold non-default values, those fields will be mutable if the instance is stored in a mutable storage location.  All fields of value-type instances stored in immutable locations will be immutable.  The only thing making a value type "mutable" or "immutable" does is affect the ease of changing its contents.


text:
Q: Deploying Gradle project on Heroku The problem is when I have the project deployed on Heroku after running
heroku local web

it would show the following
C:\Users\Richer\OneDrive\Project>heroku local web
5:22:24 PM web.1 |  Error: Could not find or load main class $JAVA_OPTS
[DONE] Killing all processes with signal  SIGINT
5:22:25 PM web.1 Exited with exit code null

and if I run
heroku ps

the shell will show
C:\Users\Richer\OneDrive\Project>heroku ps
Free dyno hours quota remaining this month: 549h 21m (99%)
Free dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:https://devcenter.heroku.com/articles/dyno-sleeping

=== web (Free): java -Dserver.port=$PORT $JAVA_OPTS -jar build/libs/*.jar (1)
web.1: crashed 2018/10/12 17:22:22 +0300 (~ 14m ago)

my Procfile looks like this
web: java -Dserver.port=$PORT $JAVA_OPTS -jar build/libs/*.jar

If it helps I have two java classes at src/main/java folder as it should be and after many attempts to upload and tun the project I've also built a jar file and its location is at out/artifacts/1_jar/1.jar though this didn't help.
So what do I do?
In addition, to successfully build a project I had to put this 3 strings in the build.gradle as it was described here
ask stage(dependsOn: ['build', 'clean'])
build.mustRunAfter clean
heroku config:set GRADLE_TASK="build"

A: On Windows, environment variables are used with the $ notation. You'll need to create a second file called Procfile.windows with the contents:
web: java -Dserver.port=%PORT% %JAVA_OPTS% -jar build\libs\*.jar

Then run heroku local web -f Procfile.windows
But leave the $ for Heroku, which uses Linux.


text:
Q: Node Express app.get working on Mac but not Windows app.get("/test", function(req, res, next) {
  res.sendFile(__dirname + '/test.html');
});

Pretty basic, yes? Running this server on my Mac this works fine. Running this server on a PC my browser receives "cannot GET" error. I don't think the issue is the permissions on the mp4 file, they seem to be ok.

A: Sorry guys, not sure what I did differently but it is working now!
For the record, here is the full app:
var express = require('express');
var app = express();

app.use(express.static('dist'));

app.get("/demo", function(req, res, next) {
  res.setHeader('Content-Type', 'video/mp4');
  res.sendFile(__dirname + '/demo.mp4');
});

var server = app.listen(80, function () {});


text:
Q: Deploying file in external storage (Xamarin, Android) I want to deploy file into external storage of this project.
For example Embarcadero RadStudio as a deployment mechanism (Project -> Deployment)
There is similar question about  Android studio. Android Studio Deployment of "External" Files
Do i have to code this manualy as Android studio? Or is there a mechanism of deployment as Embarcadero RadStudio?


text:
Q: Subtract in set intervals across 2 values in Excel I am trying to write a PTO calculator in Excel and need help subtracting paid time off.  The part I can't get to work is it subtracts in quarter-hour increments, but instead of using an HH:MM format, the times are scaled to 100.
Example:
    |     A        |  B
  --|--------------|--------
   1| Bank         |50.00
   2| CY           | 6.40
    |--------------|--------
   3| Used         | 9.50
    |--------------|--------
   4| Bank Remain  |
   5| CY Remain    |

The Used would subtract from CY Accrued first until it is less than 0.25, then it will subtract the rest from Bank Accrued.
Thanks for the help.  I did look for similar questions, but the only ones I saw calculated time in standard format (15 min intervals) not time proportioned to a 100 scale.

A: This assumes using a formula instead of VBA and I have laid out the data in a simple table (see below) where the CY Old Balance is in cell B2.
| |     A       |  B   |   C   |    D     |
| |-------------|------|-------|----------|
|1|             | CY   | BANK  | PTO Used |
|2| Old Balance | 6.4  | 50    | 9.5      |
|3| New Balance | 0.15 | 46.75 |          |

The formula for the CY New Balance cell (B3) is:
=IF(B2>=D2,B2-D2,B2-0.25*INT(B2/0.25))

If the CY Old Balance is greater than or equal to the PTO Used, then I have assumed that the entire used amount is subtracted.
The B2-0.25*INT(B2/0.25) portion calculates how many whole portions of .25 are in your Old Balance and then subtracts that from your Old Balance giving you the CY New Balance.
The formula for the BANK New Balance cell (C3) is similar:
=IF(B2>=D2,C2,C2-(D2-0.25*INT(B2/0.25)))

The first part of the IF is based on the same assumption as above.
The C2-(D2-0.25*INT(B2/0.25)) uses the same "whole portions of .25" approach, then subtracts that from PTO Used to get what remains.  That is then subtracted from BANK Old Balance to get the New Balance.

A: I'm not sure if this should go in it's own answer or not, since the principle is the same as the answer from @ReyJuna, but the execution is somewhat different.  Using the table from the question:
    |     A        |  B
  --|--------------|--------
   1| Bank         |50.00
   2| CY           | 6.40
    |--------------|--------
   3| Used         | 9.50
    |--------------|--------
   4| Bank Remain  |46.75
   5| CY Remain    | 0.15

Starting with finding CY Remain, if CY is greater than Used you don't have to worry about running out of 0.25 increment segments, so you can directly subtract using B2-B3 in the function below.
When CY is less than Used, you only want groups of exactly 0.25, so you can use the TRUNC() function to drop the decimals.  The function is:
=IF(B2<B3,B2-(TRUNC(B2/0.25)*0.25),B2-B3)
Since you want to stop subtracting at CY less than 0.25, all you have to do is get the number of 0.25 groups in CY and subtract that.  The rest that needs to be subtracted from Bank will be handled by this function:
=IF(B2<B3,B1-(B3-TRUNC(B2/0.25)*0.25),B1)
Notice the TRUNC(B2/0.25)*0.25 is the same, but is now subtracted from the value in Used.  This gives you what is left over after the correct amount has been subtracted from CY first.  Finally, when the Bank Remain function is false, meaning Bank PTO is not needed, then B1 is returned as it went unchanged.


text:
Q: non-static method generatePublic(KeySpec) cannot be referenced from a static context I am getting the above error in this particular line of code:
KeyFactory keyFactory=keyFactory.getInstance(keyAlgorithm);

        EncodedKeySpec privateKeySpec=new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey1=keyFactory.generatePrivate(privateKeySpec);

To be precise this is the error I get:
GeneratePublicPrivateKeys.java:35: error: non-static method generatePublic(KeySp
ec) cannot be referenced from a static context
PublicKey publicKey1=KeyFactory.generatePublic(publicKey
Spec);

Note: I have gone through these posts
"Non-static method cannot be referenced from a static context" error
non static method cannot be referenced from a static context
and some more and I have tried the solutions provided there,but no they do not solve my problem
What should I do?
Thankyou in advance:)

A: Try to change this line:
PublicKey publicKey1=KeyFactory.generatePublic(publicKey
Spec);

to
PublicKey publicKey1=keyFactory.generatePublic(publicKey
Spec);

A: You need to change
KeyFactory.generatePublic(...)

to be:
keyFactory.generatePublic(...)

At the moment your code is trying to call the generatePublic method as if it were static (ie associated with the KeyFactory class, rather than with an object of that type). You need to call this method on a specific instance of the class - presumably the keyFactory object refered to in your first code snippet.


text:
Q: I have a json object. I want to access in java service. I am trying to parse it I am using import net.sf.json.JSONObject
My object is like this:
[{
    "courseId": "AUTO_CAD",
    "strDate": "02-04-2012"
 }, {
    "courseId": "CNC_PROG",
    "strDate": "03-04-2012"
}]

Please help me how to access this in java service
//The code that i have tried.
List<JSONObject> jsonList = new ArrayList<JSONObject>();
jsonList = (List<JSONObject>) context.get("courseData"); // courseDate is my json object
JSONObject obj = jsonList.get(0);
Debug.log("courseStartDate ="+ obj.getJSONObject("courseId"));

//Using this gives me the following error. org.ofbiz.webapp.event.EventHandlerException: Service invocation error (java.lang.String cannot be cast to net.sf.json.JSONObject)

A: You can do this:
JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
System.out.println(pilot.getString("aKey"));

A: Here you have an ArrayList yourObject
for (int i = 0; i < yourObject.size(); i++) {
 System.out.println(yourObject.get(i).getCourseId());
 System.out.println(yourObject.get(i).getStrDate());
}

A: Have not tested yet the code, but worth a try:
JSONArray courses = new JSONArray(json);

JSONObject first = courses.getJSONObject(0); //Or access in a loop using courses.length()
Debug.log("CourseID: "+ first.getString("courseId"));