text:
Q: Showing that intersection multiplicity at a point is finite for prime divisors My question has two parts two it: one vaguely more elementary, one perhaps less so.
In Beauville (Complex Algebraic Surfaces), we define the multiplicity of intersection of two (irreducible, no common component) curves $C,D$ on a surface by first taking the intersection multiplicity of them at a point $x \in C \cap D$:
$$m_x(C,D) = \mbox{dim}_k \mathcal{O}_x/(f,g),$$
where $f, g$ are local equations for $C,D$ at $x$, and the dimension on the right is as a $k$-vector space.
Beauville claims this is finite dimensional from the Nullstellensatz, using that $f,g$ vanish on $x$ so that $M_x$ in $I(V((f,g))) = \sqrt {(f,g)}$, where $M_x$ is the maximal ideal defining $x$. This gives that $M_x^k \subset (f,g)$ for some $k$. I'm not sure how this then gives the answer: it doesn't seem far off, but I can't finish. Could anyone point me in the right direction on how to conclude?
Secondly, I'm trying to extend this to effective divisors on a surface, defined as a (nonsingular) dimension 2 projective scheme over a field $k$, as in Hartshorne. The same definition certainly works, as Hartshorne uses it: but he sidesteps showing finiteness by showing this agrees with his more technical previous definition.
Without the Nullstellensatz, I'm vaguely lost for even a starting point. Any pointers on how to begin to go about this?
Thanks!

A: This is not a complete answer, I'd like to hear suggestions for completing it.
Let $(R,m)$ be a (regular) local $\mathbb{C}$-algebra (this is the case since in Beauville, $S$ is a smooth projective surface over $\mathbb{C}.$) We would like to show that $\dim_{\mathbb{C}}R/m^n < \infty$ for $n \geq 1.$ We do this by induction on $n.$
Here I think, we need to assume that $x \in S$ is a closed point. I'd like to hear suggestions for dropping this assumption.
For $n=1,$ in fact $R/m$ is a finite algebraic extension of $\mathbb{C},$ hence is $\cong \mathbb{C}.$
For $n=2,$ look at the following short exact sequence of $R$-modules, ($\mathbb{C}$-modules)
$$0 \to m/m^2 \to R/m^2 \to R/m \to 0$$
Since $\dim_{\mathbb{C}}$ is additive, we get $\dim_{\mathbb{C}}(R/m^2) < \infty.$ Note that $\dim_{\mathbb{C}}(m/m^2)$ is finite ($S$ is smooth.)
Now for $n=3,$ we have $0\to m^2/m^3 \to R/m^3 \to m/m^2 \to 0$ so it's enough to show that $m^2/m^3$ is finite dimensional. Look at the following SES
$$0 \to m^2/m^3 \to m/m^3 \to m/m^2 \to 0$$
In fact, we have $m/m^3 \otimes_R R/m \cong \frac{m/m^3}{m(m/m^3)}\cong m/m^2$ which is also a $\mathbb{C}$-module isomorphism. I think, we can conclude that $\dim_{\mathbb{C}}m/m^3 < \infty.$ Therefore, $\dim_{\mathbb{C}}(R/m^3)< \infty.$ The same holds for $n$ with the required inductive steps.


text:
Q: Reading multiline variables from a text file in Python I am reading in a text file into python.  The text file contains a (large) number of variables with the variable name given as a string on the left and the value on the right, separated by an equals sign (=).  For example
Proc_Method = 2
Obs_Method = 4

So long as the value of the variable is given in a single line I am able to read out the value of the variable correctly with:
    namevalue = data.split('=')
    name = namevalue[0].strip()
    value = namevalue[1].strip()

However, if the variable is spread over multiple lines (i.e. an array).  This code only assigns the FIRST row of the array to the variable before moving on to the next variable.  So if I had a variable of the following form:
Corr_Mat = 10 0 0
           20 10 0
           0 20 10

the above code would state that value equaled 10 0 0 and then move on to the next variable.
Is there a way I can define value so that it takes ALL the lines starting with the equal sign, and finishes at the line before the next equality in the text file?

A: With a file like this:
Proc_Method = 2
Obs_Method = 4
Corr_Mat = 10 0 0
           20 10 0
           0 20 10
Proc_Method = 2

Option 1
You can follow a stack-like approach that puts new variables as keys into the dictionary variables and appends all following lines as value to the key.
variables = {}

with open('file.txt') as f:
    for line in f:
        if '=' in line:
            # add a new key-value pair to the dictionary,
            # remember the current variable name
            current_variable, value = line.split('=')
            variables[current_variable] = value
        else:
            # it's a continued line -> add to the remembered key
            variables[current_variable] += line

Result:
{'Proc_Method ': ' 2\n',
 'Obs_Method ': ' 4\n',
 'Corr_Mat ': ' 10 0 0 \n           20 10 0\n           0 20 10\n'}

Option 2
Alternatively, you can read the file as a whole and use a regular expression to extract the variables.
The pattern searches for the start of a line (leading ^ in combination with re.MULTILINE), followed by an arbitrary number of symbols (.+) followed by = followed by an arbitrary number of symbols that are not equal signs ([^=]+) followed by a newline.
import re

with open('file.txt') as f:
    file_content = f.read()

chunks = re.findall(r'^.+=[^=]+\n', file_content, flags=re.MULTILINE)

Result:
['Proc_Method = 2\n',
 'Obs_Method = 4\n',
 'Corr_Mat = 10 0 0 \n           20 10 0\n           0 20 10\n',
 'Proc_Method = 2\n']

Of course that needs some cleaning and only works if variables don't contain any =s which might not be guaranteed.

A: Try this code.
params = {}

last_param = ''

for line in data.splitlines():

    line = line.strip()

    if '=' in line:
        sp = line.split('=')
        last_param = sp[0]
        params[last_param] = sp[1]
    else:
        params[last_param] += f'\n{line}'

print(params)

Result:
{'Proc_Method ': ' 2', 'Obs_Method ': ' 4', 'Corr_Mat ': ' 10 0 0\n20 10 0\n0 20 10'}

A: I got a cleaner result with this but arguably messier code. But I guess there are many easy ways to make this code cleaner...
File Input:
Proc_Method = 2
Obs_Method = 4
Corr_Mat = 10 0 0
           20 10 0
           0 20 10
test = 4
test2 = 4
woof = a b c
           s sdfasd sdas
           sda as a

Code:
output = {}
with open ("E:\Coding\stackoverflow\input.txt", "r") as file:
    lines = file.readlines()
    previous_full_line = 0
    for line_number, line in enumerate(lines):
        line_content = line.strip()
        if "=" in line_content:
            namevalue = line_content.split('=')
            name = namevalue[0].strip()
            values = namevalue[1].strip()
            values = values.split(" ")
            line_list = []
            for value in values:
                line_list.append(value)
            output[name] = line_list
            previous_full_line = line_number
        else:
            values = line_content.split(" ")
            new_list = []
            for value in values:
                new_list.append(value)
            output[name].extend(new_list)

print(output)

Result
{
   "Proc_Method":[
      "2"
   ],
   "Obs_Method":[
      "4"
   ],
   "Corr_Mat":[
      "10",
      "0",
      "0",
      "20",
      "10",
      "0",
      "0",
      "20",
      "10"
   ],
   "test":[
      "4"
   ],
   "test2":[
      "4"
   ],
   "woof":[
      "a",
      "b",
      "c",
      "s",
      "sdfasd",
      "sdas",
      "sda",
      "as",
      "a"
   ]
}

From this output result I guess you can use the data however you want. Knowing that all the attributes under and "key" in the dictionary "output" are in a single array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to allow None value to be accepted in dataframe in Spark 2? I have a schema something like -
val schema = StructType( Seq (
StructField( "a", StringType, true),
StructField( "b", StringType, true),
StructField( "c", StringType, true)
))

and making a dataframe like -

import scala.collection.JavaConverters._

val listrow: List[Row] = List(Row("E-001", "P-001", None), Row("E-001", "P-001", "Attending"))
val rdd = sqlContext.sparkContext.parallelize(listrow)
val df = sqlContext.createDataFrame(rdd, scm)

Now, when I do a df.first(), I get an error, the essence of which is -
java.lang.RuntimeException: Error while encoding:   java.lang.RuntimeException: scala.None$ is not a valid external type for schema of string
Note that I need to create the df this way only. The above is just an example but the code in production is a bit complex. I think it used to work in Spark 1.6 but started to fail in Spark 2.0.1. Is this something to do with Encoders? Note that some of the data will always have None and the df needs to handle it. Is there a way to handle this or the data just cannot have None?
Can anyone else here too seen this and probably know what the solution is?
Thanking in anticipation!

A: You can replace the None with null.asInstanceOf[String]:
val listrow: List[Row] = List(Row("E-001", "P-001", null.asInstanceOf[String]), Row("E-001", "P-001", "Attending"))

scala> df.show
+-----+-----+---------+
|    a|    b|        c|
+-----+-----+---------+
|E-001|P-001|     null|
|E-001|P-001|Attending|
+-----+-----+---------+

Or go with what was mentioned before and use a case class that uses Option[String] for that 3rd value:
case class Foo(a: String, b:String, c:Option[String])

val listFoo: List[Foo] = List(Foo("E-001", "P-001", None), Foo("E-001", "P-001", Some("Attending")))
listFoo.toDF.show
+-----+-----+---------+
|    a|    b|        c|
+-----+-----+---------+
|E-001|P-001|     null|
|E-001|P-001|Attending|
+-----+-----+---------+


text:
Q: Refresh the Gridview I am updating the table in database by entering some fields in same page containing INPUT fields and Grid. but grid which is connected to that table is not refreshing after submit the value. I have to open that page in new tab to view the changes. Also i want those input fields empty after submit.
               <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                ConnectionString="<%$ ConnectionStrings:con %>"
                ProviderName="<%$ ConnectionStrings:con.ProviderName %>"
                SelectCommand="SELECT * FROM [View_Intakesheet]"
                InsertCommand="INSERT INTO [View_Intakesheet] [date_withdrawn], [date_delivered], [qc_by], [qc_date], [additional_notes], [Case_Status_Text], [Case_Type_Text]) VALUES (@date_withdrawn, @date_delivered, @qc_by, @qc_date, @additional_notes, @Case_Status_Text, @Case_Type_Text)"
                UpdateCommand="UPDATE intakesheet SET date_withdrawn= @date_withdrawn, date_delivered= @date_delivered, qc_by = @qc_by,  qc_date=@qc_date, additional_notes = @additional_notes WHERE (case_number = @case_number)">
                   <InsertParameters>
                    <asp:Parameter Name="date_withdrawn" />
                    <asp:Parameter Name="date_delivered" />
                    <asp:Parameter Name="qc_by" />
                    <asp:Parameter Name="qc_date" />
                    <asp:Parameter Name="additional_notes" />
                    <asp:Parameter Name="Case_Status_Text" />
                </InsertParameters>
                <SelectParameters>
                    <asp:SessionParameter Name="assigned_to" SessionField="Name" Type="String" />
                </SelectParameters>
                <UpdateParameters>
                    <asp:Parameter Name="case_status" />
                    <asp:Parameter Name="date_withdrawn" />
                    <asp:Parameter Name="date_delivered" />
                    <asp:Parameter Name="qc_by" />
                    <asp:Parameter Name="qc_date" />
                    <asp:Parameter Name="additional_notes" />
                    <asp:Parameter Name="case_number" />
                    <asp:Parameter Name="case_type" />
                </UpdateParameters>
            </asp:SqlDataSource>

A: You can do it by rebinding the gridview like this just after where your update is done.
GridViewIs.DataBind()

A: You will have to re-bind the grid once you are done with changes. Please let us know if you are doing that.


text:
Q: Build failed after adding Hilt components in Android project I was trying to explore Hilt with simplest possible example, but my application isn't building. I added all the dependencies but when I try to build, it shows an error indicating not finding the hilt gradle plugin.
Here are my codes:
build.gradle(project)
    ext.kotlin_version = "1.5.20"
    ext.hilt_version = '2.35'
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(app)
plugins{
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.bonny.tutorial.hilttest"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.5.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    //hilt
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

Application Class (included in the Manifest too)
import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class TextApplication : Application() {
}

Dependency class (MyTexts.kt)
class MyTexts @Inject constructor(){
    val text = "Hello World"
}

MainActivity.kt
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var tv: TextView
    @Inject lateinit var myTexts: MyTexts
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv = findViewById(R.id.myText)
        tv.text = myTexts.text
    }
}

and the error looks like this:
public final class MainActivity extends androidx.appcompat.app.AppCompatActivity {
             ^
  Expected @AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

Please suggest.

A: Kotlin 1.5.20 just came out (24 jun 2021) so there seems to be some compatibility issue. You can bring down to  ext.kotlin_version = "1.5.10" in your build.gradle(project)
Also, Update hilt to latest 2.37
project build
classpath "com.google.dagger:hilt-android-gradle-plugin:2.37"

app build:
//Dagger - Hilt
    implementation "com.google.dagger:hilt-android:2.37"
    kapt "com.google.dagger:hilt-android-compiler:2.37"


text:
Q: Can't get the name of a related table column I'm just starting to learn SQL, and so far (since two days ago) i managed to solve most of my problems, but now i need help.
The query below results in 1 column and row: "12345" and some extra rows with the value 0, that i need to get rid of.
SELECT product_id FROM sale_order_line WHERE order_id IN (SELECT id FROM sale_order WHERE name='S00062')

So i tried the following:
SELECT product_id FROM sale_order_line WHERE order_id IN (SELECT id FROM sale_order WHERE name='S00062') AND NOT product_id='0'

And now i get the result '12345' i was expecting.
But when i try to get the name of the the column related to '12345' from another table....:
SELECT name FROM product_template WHERE product_variant_ids IN (SELECT product_id FROM sale_order_line WHERE order_id IN (SELECT id FROM sale_order WHERE name='S00062') AND NOT product_id='0')

I get an error saying: "Cannot compare data type of integer to string".
Somehow it appears the code above tries to read product_id with all the 0s before they're all removed. I'm guessing.
But, if i do it directly, like:
SELECT name FROM product_template WHERE product_variant_ids = '12345'

It works!
How can i fix this?
Please forgive my newbie coding skills.

A: It would seem that product_template.product_variant_ids and sale_order_line.product_id are of incompatible data type, one of integer and the other a string type (text, varchar, ...) -  as the error message indicates.
Make it a habit to table-qualify all column names in queries involving multiple columns.
Guessing from the column names, product_id is integer, and product_variant_ids is a string type, which is most probably a design error. If it actually holds a single valid integer in string representation, like your final query suggests, then making some more assumptions about PK constraints in your data model, your query could work like this:
SELECT pt.name
FROM   sale_order       so
JOIN   sale_order_line  sol ON sol.order_id = so.id
JOIN   product_template pt  ON pt.product_variant_ids::int = sol.product_id  -- !
WHERE  so.name = 'S00062'
AND    NOT sol.product_id = 0;  -- numeric literal without

Note the cast to integer: product_variant_ids::int. But this is just putting lipstick on a pig. The column should be type integer to begin with.
Then again, the name product_variant_ids indicates multiple values, hinting at int[], an array of integer. Then you need to do more ...
Use JOIN notation instead of nesting multiple levels of x IN (subquery). Much simpler, and typically much faster.
Both are identical as long as the subquery returns distinct values. Else, the IN notation folds duplicates, while joins do not. This difference also makes x IN (subquery) more sophisticated to execute internally and hence more expensive.
Finally, a column named product_variant_ids typically indicates misguided database design in any case. Typically, you don't cram multiple values in a single column. If that column has a string type on top of it, that's a double no-no. You have to look into relational design and database normalization some more.


text:
Q: Convergence of a finite continued fraction Given a sequence of natural numbers $(a_n)_{n\geq 1}$, we know that the finite continued fraction
$$[a_1,a_2,\ldots,a_n]:=\cfrac{1}{a_1+\cfrac{1}{\ddots+\cfrac{\ddots}{a_{n-1}+\cfrac{1}{a_n}}}}$$
is convergent when $n\to\infty$. My question is: what about the convergence of the reverse finite continued fraction $[a_n, a_{n-1},\ldots, a_1]$?

A: Not necessarily.  An easy counterexample: $a_n = 1$ if $n$ is even, $2$ if $n$ is odd.

A: Intuitively, it should be clear that the reverse variant does not converge. The point is that for the normal case, "the influence of a new number" vanishes in the limit, while in the reverse case "the last number" has a massive influence.
Just take the sequence $K_n = [1,2,1,2,1,2,1,2......]$ such that $K_n$ has $n$ elements (cardinality). Consider these two for the normal case:
\begin{equation}
[1,2,1,2,1....] \to \frac{1}{1+\frac{1}{2+\frac{1}{1 + ...}}}\end{equation}
\begin{equation}[2,1,2,1,2....] \to \frac{1}{2+\frac{1}{1+\frac{1}{2 + ...}}}\end{equation}
These are not equal. Considering this, we see that in the reverse case, $K_n$ and $K_{n+1}$ would always be different, and won't converge.
To make it more extreme you could use a larger number, instead of 2.


text:
Q: Mysql Join condition connecting two databases in the same server select first_name, last_name, amount, payment_date
from customer_db.customer_data c
join employee_db.payment e
on c.customer_id= e.payment_id
where customer_db.customer_data(customer_id)='6';

I am getting
12:05:54    select first_name, last_name, amount, payment_date  from customer_db.customer_data c join employee_db.payment e on c.customer_id= e.payment_id  where customer_db.customer_data(customer_id)='6' LIMIT 0, 1000
Error Code: 1305. FUNCTION customer_db.customer_data does not exist 0.000 sec

A: you're trying to call a function:
where customer_db.customer_data(customer_id)='6';
                               ^-----------^

Perhaps you meant
where customer_db.customer_data.customer_id='6';
                               ^---

instead?

A: You use alias for table in your query so you must replace this:
customer_db.customer_data.customer_id

With
c.customer_id

A: select customer_db.customer_data.first_name, customer_db.customer_data.last_name, employee_db.payment.amount, employee_db.payment.payment_date
from customer_db.customer_data
inner join employee_db.payment
on customer_db.customer_data.customer_data_id = employee_db.payment.payment_id
where customer_db.customer_data.customer_data_id ='6';

I finally found the solution. Thannks


text:
Q: How to program frames in C++ OK, C++ noob here asking a very nooby question (sorry) but whenever I write my basic programs (helloworld etc.) they always appear in a command prompt window. I want to make proper windows like in Word and other programs. I know it is possible to do this because of all the programs I use every day. But how do I do this in C++? For all the Java veterans out there, I want it to be like a JFrame, but the C++ equivalent.

A: C++ doesn't have a UI library out of the box, so you need to choose one.
Popular options would be MFC (under Windows/Visual C++) or Qt (with quite a lot additional libraries and features, working on many platforms).

A: Since you mention Word, it appears that you're on the Windows platform.
Then consider starting with e.g. the Lessons in Windows API Programming (C++) hands-on tutorial.
There are also a great many other tutorials on the net, and books to buy. I just picked the one that I was most familiar with, as the author. Regarding books, the classic book on programming the Windows API is Petzold's "Windows Programming", but I seem to recall that the latest version is for Windows 8 and in C# (earlier version were C/C++).
The tutorial leads you through how to get started with creating window programs using the Windows API (Application Program Interface) direcetly.
This is fairly language independent, but the language used in the tutorial is C++. C++ doesn't have standard library support for GUI stuff. The idea in C++ is that you're free to use whatever third party libraries that you want, or create them, such as the Windows API.

A: This is highly platform dependent. You can use a GUI cross-platform library, like QT, or use native mechanisms. Under Windows you can use the WinAPI and MFC.


text:
Q: Epub and android. How to get part of html and fit it in webview I am developing a reader and I encountered a problem. I want to open epub files into webview. But I don't know how to get such number of text for fitting in webview as 1 page. I think I need to devide html files from epub. But how ? Help me please.

A: try to use epub.js. It'JS library for epub pagination with TOC and bookmarks.


text:
Q: I'm having some trouble while setting MongoDB to run on the cloud I'm new to Node.Js and all of its "accessories", and I've been trying to set up a Mongodb database, but there are so many ways to do it, it seems, that I've been quite stuck because I'm not sure what goes where and when, anyway, I have a snapshot of the code and the prompt, everything else on the code works.

Also I want to use the mongo cloud database while hosting my node.js on heroku (I got the heroku deployment running), so would I be able to test my database both when doing "node app.js" on my local machine and when I deploy it on heroku?
Additional information:

I NPM'ed mongojs and mongodb
I'm using some sort of cluster on mongodb.atlas (I'm clueless on this)
I set up the mongodb shown on the snapshot above using the option: Clusters > Connect > Connect your application > Short SRV connection string

A: I had a similar situation with MongoDB working on Heroku but not locally, getting that same error message. Here's the steps I took.

*

*Make sure the database path is configured correctly - it is /data/db by default. I had to run mkdir -p /data/db; you can also choose to manually set that path.

*Make sure that MongoDB is running locally before you start your server. You may have to run mongod in the command line to start it; alternately, for Node.js, you can go to package.json and edit your launch configuration by adding "pre-start: 'mongod'" to "scripts," which automatically starts MongoDB when you start your server.


text:
Q: Find correct ACPI drivers without trial-and-error My system is running on a minimal kernel config (based on make defconfig).
Now I'm trying to figure out which extra acpi device drivers I have to enable to get everything on my system working. To find a matching driver I could enable it, build & restart, observe dmesg. This is a tedious and error-prone process, and I'd like to be able to choose the correct drivers based on system information.
For PCI or USB devices I was able to utilize lspci -nn and searched for the vendorId:deviceId in LKDDb.
I have seen ACPI entrys in this database too, but cannot figure out how to extract ACPI device information from my system.

A: The solution is to dump and decompile the ACPI DSDT (Differentiated System Description Table) from the BIOS. This includes code for ACPI device initialization specific to the used system, and therefore also includes the necessary device ids.
Decompile the DSDT with the following commands (iasl must be installed)
cp /sys/firmware/acpi/tables/DSDT dsdt.dat
iasl -d dsdt.dat

Then query the decompiled code for device ids
grep '_HID.*"' dsdt.dsl

The output will include all lines where a device is declared, and the respective device ids. Finally utilize LKDDb to find the necessary kernel acpi drivers for the devices.
For a quick extraction of the relevant lines you can use this:
wget https://cateee.net/sources/lkddb/lkddb.list
for i in $(grep '_HID.*"' dsdt.dsl | grep -o '"[A-Z0-9]*"'); do grep "$i" lkddb.list; done | sort -u > relevant

Furthermore list all CONFIG_* variables from the output:
cat relevant | grep -o 'CONFIG[A-Z0-9_]*' | sort -u

Note that this list is only a guidance, and does not guarantee to be free of false positives or false negatives. If you want to be sure about what you are doing, you should investigate the dsdt.dsl yourself.


text:
Q: How to recover from failed installment of codelite My system initially is ubuntu 12.04. I installed codelite yesterday by running "apt-get install codelite", it worked fine. I noticed that it is not the latest version and tried installing the latest manually, but this introduced problem.
I followed the instruction from codelite web page:
sudo apt-key adv --fetch-keys http://repos.codelite.org/CodeLite.asc
sudo apt-add-repository 'deb http://repos.codelite.org/ubuntu/ trusty universe'
sudo apt-get update
sudo apt-get install codelite

But I got dependency error just like this one.
I then tried several suggestions, the latest is Howto install the latest codelite in Ubuntu - EuroBytes. But I missed the note about "amd64" and "i386" initially and after I corrected, there still problem.
Anyway, I give up installing the latest version at this point, but I found that I cannot go back now - I uninstalled codelite in the beginning - when I run "apt-get install codelite" again, I get the following error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 codelite : Depends: libpango-1.0-0 (>= 1.18.0) but it is not installable
            Depends: libpangocairo-1.0-0 (>= 1.14.0) but it is not installable
            Depends: libtiff5 (>= 4.0.3) but it is not installable
            Depends: libwxbase3.0-0 (>= 3.0.0) but it is not installable
            Depends: libwxgtk3.0-0 (>= 3.0.0) but it is not installable
E: Unable to correct problems, you have held broken packages.

Could you point me how I can recover from this?

A: I'm the author of Howto install the latest codelite in Ubuntu - EuroBytes. I have tested the latest codelite on Trusty.
If you still have issues with codelite, remove like so: sudo apt-get purge codelite
Note that the dependencies links are dead. But, I managed to install it anyway:

Codelite 6.1 on Ubuntu Trusty Thar 14.04.
Image from: Howto install the latest codelite in Ubuntu - EuroBytes

Install like so:
sudo apt-add-repository "deb http://repos.codelite.org/ubuntu/ $(lsb_release -sc) universe"
sudo apt-key adv --fetch-keys http://repos.codelite.org/CodeLite.asc
sudo apt-get update
sudo apt-get install codelite wxcrafter

Feel free to contact me here, or on my website, for any issues you may have.
Source:

*

*Howto install the latest codelite in Ubuntu - EuroBytes


text:
Q: Non-capturing lookbehind regex match is not working Problem statement is as follows.
my description is
abc abcxxyz 10xabc abcx10 abc10xabc abcx10xyz
want the regex which will match abc only if it is preceded by digit + x or succeeded by x + digit.
In above example it should match abc from abcx10 , 10xabc and abcx10xyz
but should not capture digits in those matches.
that means while replacing text it should replace only abcx or xabc.
Have tried (((((?:\d+)))[Xx]))(abc)(\s|$|(([Xx](?=((\d).)+)))|[^a-zA-Z0-9]) but it is not excluding digits from capturing.
Thanks.

A: Try this:
((?<=\d[Xx])abc)|(abc(?=[Xx]\d))

Demo here
Notice that the lookbehind cannot have any quantifiers - it has to have known and defined length.
If you want to get abcx and xabc, there is slightly different version:
https://regex101.com/r/cD5hI6/2


text:
Q: Finding edge cases and solving for circular queues and circular permutations I have a circular queue for example {1,2,3,4,5,6}
Now a pattern is given to me so i have to find if its split from the circular queue.
For example if i'm given a pattern such as {4,5,6,1,2,3} then yes its split from the circular queue.
If i'm given another patter such as {4,3,2,1,6,5} then yes it's split from the circular queue.Here i have displayed the two possible test cases that i can think of.
Another example would be if i'm given a {4,5,6,2,3,4} or {7,6,5,3,4,5} which are both not split from the circular queue.
Just wanted to if any one can find any more possible test cases for this problem.

A: Having a pattern "split from a circular queue" is not standard terminology, but supposing that you mean there is a sequence of entries in the queue matching the pattern, here are three more cases to try:
• Any queue, empty pattern – should match
• Empty queue, not-empty pattern – should not match
• With queue={1,2,3}, pattern {1,2,3,1,2} – should match


text:
Q: How to pass functions as props in Qwik JS? Problem
In React, we can pass functions as props into a child component when a function requires access to a state within the parent component of the aforementioned child. I was writing code for an application where I need such behavior to be implemented. However, I'm having trouble finding proper conventions for defining functions in Qwik, and then sending them through.
Attempt
I've tried defining the function within my interface to see if that helps Qwik to allow this implementation but so far that has not worked either.
Code
I'm trying to launch a modal from a icon contained in the header within my application. I'm trying to control displaying the modal by using a store declared within my header component. It's a Boolean value and determines if the modal would be displayed or not. I defined the function for modifying the state within my header component and attempted to pass it into my modal child component.
// components/header/header.tsx
import { component$, useClientEffect$, useStore } from "@builder.io/qwik";
import { strictEqual } from "assert";
import Modal from "../modal/modal";

export default component$(() => {
    const store = useStore({
        ...
        modal: false
    });

    function onClose() {
        store.modal = false;
    }

    return (

            {store.modal && <Modal onClose={onClose}/>}

{
                    store.modal = true;
                }}
            >

    );
});

Inside my modal component I tried to use an interface to indicate that I'm passing a function into my props and tried to set as the function to execute within another icon contained within my child component.
// components/modal/modal.tsx
import { component$ } from "@builder.io/qwik";
import { strictEqual } from "assert";

interface ModalProps {
    onClose: () => void
}

export default component$((props: ModalProps) => {
    return (

Modal

    );
});

Error Message
When I click on the icon within my header, it displays the following error in my terminal.
log.js:10 QWIK ERROR Error: Code(3): Only primitive and object literals can be serialized at Array.flatMap (<anonymous>) ƒ onClose() { store.modal = false; }
Conclusion
Is there anyway to send functions as props into child components in Qwik JS?
If not, can I access stores contained in a parent component from within a child component?
Basically, what would be the ideal approach to solve this issue?

A: As I'm a noob like you in this framework, I've struggled to understand how this works too.
You actually need to pass a QRL as you may read here:
https://qwik.builder.io/docs/components/events/
So, here's how to modify your code for the Modal component:
import { component$, QRL } from '@builder.io/qwik';

interface ModalProps {
    onClose: QRL<() => void>;
}

export default component$<ModalProps>(props => {
    return (

Modal

    );
});

And your head component:
import { $, component$, useStore } from '@builder.io/qwik';

import Modal from '../components/test';

export default component$(() => {
    const store = useStore({
        modal: false
    });

    const onClose = $(() => {
        store.modal = false;
    });

    return (

            {store.modal && <Modal onClose={onClose} />}

 {
                    store.modal = true;
                }}
            >

    );
});


text:
Q: Nagios - difference between 'CURRENT SERVICE STATE' & 'SERVICE ALERT' I am a newbie to Nagios. I googled quite a bit and read documents related to states, notifications and so on. But I did not find answer for my questions.
Could you please help me understand the difference between 'CURRENT SERVICE STATE' & 'SERVICE ALERT'.
Background:
In our Nagios screen all the hosts and their related services are displayed properly. We are planning to use nagios.log for additional tasks.
In nagios.log file, I see that there is CURRENT SERVICE STATE and SERVICE ALERT log lines which contain the necessary information that we need.
I have few questions.

*

*What is the difference between 'CURRENT SERVICE STATE' & 'SERVICE
ALERT'?

*Deep diving into the log file, i noticed that CURRENT SERVICE STATE is logged only once at 00:00 AM. Where as the SERVICE ALERT is logged randomly (There is no constant time gap between log entries for a particular Service Check)

*Even though the checks are scheduled to run every 5 minutes, the status.dat file has entries every few seconds. This makes it hard to achieve what we need. Since single service check run info is logged multiple times.

*Sometimes tail -f on nagios.log stops the log file from updating further. What could be the reason for this?

*In one setup nagios.log file is updated every 10 minutes and in one setup it is very random. IS there any configuration to handle the update schedule?

Thanks,
Mahesh

A: 1) CURRENT SERVICE STATE is the current state of the service (OK, WARNING, CRITICAL, or UNKNOWN). SERVICE ALERT will only be logged if the state of a service changes.
2) The logging of CURRENT SERVICE STATE at midnight is something to do with how your server is set up. Again, SERVICE ALERT is random because it will alert at a state change.
3) status.dat is refreshed every time a new cfg is applied. It will be updated every time a check is performed so you must have checks going out for multiple services which amounts to every few seconds. https://assets.nagios.com/downloads/nagioscore/docs/nagioscore/3/en/configmain.html
4) Either nagios.log is not updating or there is something wrong with your server's linux.
5) nagios.log is only updated when a change occurs in a host or service.


text:
Q: jQuery: select elements by style attribute I'm trying to select list of elements which have its style attribute begins with "color".
My HTML:

abc

My query:
var list= $('[style|="color"]');

var list is null after querying (1).
var list= $('[style*="color"]');

but statement (2) works well,
and
$('#idd').attr('style')

returns exact color: red; border: 1px solid black
I know that I should find elements by name or id attribute or just query if "color" appears in style (no need to match the position).
But I realy wonder why it doesn't work as my expectation.
Thank you very much,

A: [style|="color"] doesn't match because color isn't followed by dash and isn't an exact match.

[att|=val] Represents an element with the att attribute, its value
  either being exactly "val" or beginning with "val" immediately
  followed by "-" (U+002D).

SPEC

I'm trying to select list of elements which have its style attribute
  begins with "color"

So use:
var list= $('[style^="color"]');


text:
Q: Find structurally catch blocks in IntelliJ IDEA I need to find all catch blocks with one-letter catch parameters in Java code, for example:
catch (IOException e)

I've tried the following pattern and it doesn't work:
catch ($Type$ $name$)

$name$ text/regexp set to `.`

A: Possible solution 1
Try the existing template try's. Edit variable $ExceptionDcl$ to text/regexp . and enable This variable is target of the search. Try statements with multiple catch blocks will only be found once with this pattern.
Possible solution 2
To find individual catch blocks in try statements with multiple catches use:
$E$ $e$

$E$ Text/regexp: Throwable, Apply constraint within type hierarchy enabled
$e$ Text/regexp: ., Script text: __context__.parent instanceof com.intellij.psi.PsiCatchSection
Background info
It is not possible to search for lonely catch blocks. To search a language Structural Search uses the parser that is used for all other smartness in IntelliJ IDEA. This means that every pattern must be valid Java when searching for Java. Thus it is an unfortunate limitation that just a catch block is not parsed into something that can be searched for. This is also why it is not possible replace keywords with a $variable$ in an SSR pattern.


text:
Q: Could not change the content type of a Document list item in a document library I'm programatically changing the content type of a document in a document library. But document is getting added with the content type only.
Here is my coding:
SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["Content Type"] = octype.Name;
ofile.Item["Content Type ID"] = octype.Id;
ofile.Item.Update();

when i traced the above coding the content type is getting changed when i assign them to the item but after I update the the item in the last line the content type of the item is getting set to the default content type.

A: Shouldn't it be:
SPFile ofile = oweb.GetFile(oweb.Url + '/' + oDocSet.Item.Url + '/' + refName);
ofile.Item["ContentType"] = octype.Name;
ofile.Item["ContentTypeId"] = octype.Id;
ofile.Item.Update();

Note the lack of spaces in the field names
P.S.: Is the content type actually allowed in the library?

A: I had the same situation as described here. ContentType remains the same after save document in document library in custom form. Code provided above runs without exceptions and messages, but contenttype remains the same.
Problem solved with reverting back to default edit form, changing contenttype with it, and reassigning custom edit form in Sharepoint Designer again. Now contenttype changes work without problems.
Maybe it internal bug with sharepoint.


text:
Q: Catching exception from worker thread in the main thread I didn't find a concise answer to the following problem:I have a producer - consumer threading model where main thread is the consumer while some worker thread is the producer.The producer thread runs it's thread loop during the application execution and it is possible for it to throw exceptions occasionally.The main thread is UI thread which should pop-up exception messages including those coming from different threads. How can I catch these exceptions in the main thread?
Using boost on Windows with  C++0x
WorkerThread.cpp
WorkerThread::WorkerThread(){

   m_thread = boost::thread(&WorkerThread::drawThread,this);

}

void WorkerThread::drawThread()
{

         while(true)
         {
             boost::unique_lock<boost::mutex> lock(m_mutex);
              try{

                ///some work is done here...

              }catch(std::exception &e){

               /// some exception is thrown
               /// notify main thread of the exception
              }

         }

 }

Important to note that I have no ability to wrap WorkerThread in the main thread with try{}catch  as it is created at some point and from then on runs on its own till the application termination.

A: Those answer suggest you to send exception_ptr to main thread manually. That's not bad way, but I suggest you another way: std::promise / boost::promise.
(Since I don't have boost in this computer now, so I'll go with std::promise. However, there may be no big difference with boost.)
Look the example code:
#include <iostream>
#include <exception>
#include <thread>
#include <future>
#include <chrono>

void foo()
{
    throw "mission failure >o<";
}

int main()
{
    std::promise<void> prm;

    std::thread thrd([&prm] {
        try
        {
            std::this_thread::sleep_for(std::chrono::seconds(5));
            foo();
            prm.set_value();
        }
        catch (...)
        {
            prm.set_exception(std::current_exception());
        }
    });

    std::future<void> fu = prm.get_future();
    for (int i = 0; ; i++)
    {
        if (fu.wait_for(std::chrono::seconds(1)) != std::future_status::timeout)
            break;
        std::cout << "waiting ... [" << i << "]\n";
    }

    try
    {
        fu.get();
        std::cout << "mission complete!\n";
    }
    catch (const char *msg)
    {
        std::cerr << "exception: " << msg << "\n";
    }

    thrd.join(); /* sorry for my compiler's absence of std::promise::set_value_at_thread_exit */
}

The benefit of this way is 1. you don't have to manage exceptions manually - std::promise and std::future will do everything and 2. you can use all feature around std::future. In this case, I'm doing other things (outputing waiting... message) while waiting the thread exit, through std::future::wait_for.

A: Firstly, you do not need to use bind with thread. Doing so just adds unnecessary copying and makes the code harder to read. I wish everyone would stop doing that.
WorkerThread::WorkerThread(){

    m_thread = boost::thread(&WorkerThread::drawThread, this);

}

You can store an exception in an exception_ptr and pass that to the other thread, e.g. in std::queue<std::exception_ptr>:
void WorkerThread::drawThread()
{
    while(true)
    {
        boost::unique_lock<boost::mutex> lock(m_mutex);
         try{

            ///some work is done here...

         }catch(std::exception &e){
             m_queue.push(std::current_exception());
         }
    }
}

std::exception_ptr WorkerThread::last_exception()
{
    boost::lock_guard<boost::mutex> lock(m_mutex);
    std::exception_ptr e;
    if (!m_queue.empty())
    {
        e = m_queue.front();
        m_queue.pop();
    }
    return e;
}

Then in the other thread rethrow it and handle it:
if (auto ep = workerThread.last_exception())
{
    // do something with exception
    try
    {
        std::rethrow_exception(ep);
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error in worker thread: " << e.what() << '\n';
    }
}

If you can't use std::exception_ptr Boost has its own implementation of it, but I'm not sure what the Boost equivalent of current_exception is. You might need to wrap the exception in another object so the Boost exception propagation mechanism can store it.
You might want to use a separate mutex for the exception queue from the main work loop (and move the m_mutex lock inside the try block) depending how long m_mutex is usually locked by the worker thread.

A different approach uses C++11 futures, which handle passing exceptions between threads more conveniently. You need some way for the main thread to get a future for each unit of work the worker thread runs, which can be done with std::packaged_task:
class WorkerThread
{
public:
  WorkerThread();   // start m_thread, as before

  template<typename F, typename... Args>
  std::future<void> post(F f, Args&&... args)
  {
    Task task(std::bind<void>(f, std::forward<Args>(args)...));
    auto fut = task.get_future();
    std::lock_guard<std::mutex> lock(m_mutex);
    m_tasks.push(std::move(task));
    return fut;
  }

  private:
    void drawThread();
    std::mutex m_mutex;
    using Task = std::packaged_task<void()>;
    std::queue<Task> m_tasks;
    std::thread m_thread;
  };

 void WorkerThread::drawThread()
 {
    Task task;
    while(true)
    {
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            task = std::move(m_tasks.front());
            m_tasks.pop();
        }
        task();   // run the task
    }
}

When the task is run any exceptions will be caught, stored in an exception_ptr and held until the result is read through the associated future.
// other thread:

auto fut = workerThread.post(&someDrawingFunc, arg1, arg2);
...
// check future for errors
try {
   fut.get();
} catch (const std::exception& e) {
   // handle it
}

The producer thread could store the future objects in a queue when posting work to the consumer, and some other piece of code could check each future in the queue to see if it's ready and call get() to handle any exception.

A: In the worker thread, you can catch the exception, and then retrieve a std::exception_ptr using std::current_exception.  You can then store this somewhere, pick it up in the main thread, and throw it with std::rethrow_exception.

A: Exceptions are synchronous. Which means there is no way to pass them between threads as exceptions. You cannot tell to any old thread "stop whatever you are doing and handle this". (Well you can if you deliver a POSIX signal to it, but that's not quite a C++ exception).
You can of course always pass an object with the exception data (as opposed to the state of being in an exception-handling mode) to another thread in the same way you would pass any other data between threads. A concurrent queue will do. Then you process it in the target thread. The target thread should be actively reading data from the queue.


text:
Q: how to display related image names in grid hi i am new to iPhone development. what i am doing is displaying 20 images as grid and each image treat as button .by selecting that image it will be displayed on image view but what i need is along with that image,image name also displayed at bottom how can i done this pls help me i am lucky if u give a sample code also thank u

A: Put a label below the button.


text:
Q: Filtrar meses, años y días en Query Builder Symfony Estoy trabajando en symfony y tengo que hacer una consulta con query builder, y necesito filtrar una fecha por año y mes.
$query = $this->createQueryBuilder('p')
    ->select('p')
    ->where('p.almacen = :almacen')
    ->andWhere('p.estado != :cerrado')
    ->andWhere('p.estado != :cancelado')
    ->orderBy('p.id', 'ASC')
    ->setParameter('almacen', $almacen)
    ->setParameter('cerrado', 4)
    ->setParameter('cancelado', 5);

return $query->getQuery()->execute();

Pero el Query builder no reconoce un WHERE del estilo: YEAR(fecha) = x lo mismo para MONTH y DAY

He encontrado esta respuesta en stackOverflow pero me gustaría una
  respuesta que no requiera modificar archivos de configuración.

https://stackoverflow.com/questions/18826836/how-can-i-use-sqls-year-month-and-day-in-doctrine2


text:
Q: ¿Blazor maui custom icon? I'm trying to customize the blazor maui app icon. I have tried replacing the appicon.svg and the appiconfg.svg by replacing the appiconfg.svg I have customized the splash screen, but in the case of appicon.svg I have only caused a black background to appear with the .NET text. Does anyone know how to remove that .NET ?
Thanks.


text:
Q: ThreeJS: Draw lines at mouse click coordinates I am working with ThreeJS to create a solar system. I have a sun in the middle and 8 orbits around it. Now I want to get the nearest ring poisiton when the users clicks anywhere on the map!
Here is an image to describe it visually what I mean
The arrows stands for the "click" of the user, then there should be a function to get the nearest orbit and its coordinates (the white dots) where the line between the click point and middle collides.
I tried many different functions I found here, but non of them gave me the result I want.
Thanks for your help!
The code looks currently like this:
            var container, stats, parent, pivots, domEvents, twins, planets, sun, fleets, raycaster, mouse;
            var camera, controls, scene, renderer;
            var cross;
            planets = new Array();

            init();
            animate();
            function init()
            {

                raycaster = new THREE.Raycaster();
                mouse = new THREE.Vector2();

                //init
                camera = new THREE.PerspectiveCamera(10, 1, 1, 4000);
                camera.position.z = 200;
                camera.position.x = 200;
                camera.position.y = 200;
                controls = new THREE.OrbitControls(camera);
                controls.addEventListener('change', render);
                scene = new THREE.Scene();
                scene.fog = new THREE.FogExp2(0x000000, 0);

                // renderer
                renderer = new THREE.WebGLRenderer({antialias: false, alpha: true});
                renderer.setSize(document.getElementById('canvasreference').offsetWidth, document.getElementById('canvasreference').offsetWidth);
                renderer.setClearColor(0x787878, 0.5); // the default

                container = document.getElementById('canvasreference');
                container.appendChild(renderer.domElement);
                window.addEventListener('resize', onWindowResize, false);
                domEvents = new THREEx.DomEvents(camera, renderer.domElement);

                //axihelper
                scene.add(new THREE.AxisHelper(130));

                // parent
                parent = new THREE.Object3D();
                scene.add(parent);

                //arrays
                orbits = new Array();

                addOrbit();

                window.addEventListener('click', onMouseMove, false);

            }

            function onMouseMove(event) {
                    canvas = renderer.domElement;
                raycaster = new THREE.Raycaster();
                mousePosition = new THREE.Vector2();
                canvasPosition = $("#canvasreference canvas").position();
                console.log(canvasPosition);
                mousePosition.x = ((event.clientX - canvasPosition.left) / canvas.width) * 2 - 1;
                mousePosition.y = -((event.clientY - canvasPosition.top) / canvas.height) * 2 + 1;

                raycaster.setFromCamera(mousePosition, camera);

                 var geometry = new THREE.Geometry();
                 var origin = new THREE.Vector3(raycaster.ray.origin.x, 0, raycaster.ray.origin.y);
                 geometry.vertices.push(origin);

                 var vektor = new THREE.Vector3(raycaster.ray.direction.x, 0, raycaster.ray.direction.y);

                 for (var i = 0; i < 1000; i++)
                 {
                 origin.add(vektor);
                 geometry.vertices.push(vektor);

                 }

                 var material = new THREE.LineBasicMaterial({
                 color: 0xffffff, linewidth: 20
                 });

                 var line = new THREE.Line(geometry, material);

                 scene.add(line);
                 renderer.render(scene, camera);

            }

            function onWindowResize() {

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(600, 600);
                render();
            }

            function animate() {

                requestAnimationFrame(animate);
                controls.update();

                renderer.render(scene, camera);
            }

            function render() {
                renderer.render(scene, camera);
            }

            /**
             * add Orbit line
             * @param {type} orbit
             * @returns {undefined}
             */
            function addOrbit(orbit)
            {
                for (var i = 0; i < 8; i++)
                {
                    //make orbit line
                    var orbit = new THREE.EllipseCurve(
                            0, 0, // ax, aY
                            i * 10 + 30, i * 10 + 30, // xRadius, yRadius
                            0, 2 * Math.PI, // aStartAngle, aEndAngle
                            false, // aClockwise
                            0                 // aRotation
                            );
                    var path = new THREE.Path(orbit.getPoints(100));
                    var geometry = path.createPointsGeometry(100);
                    var material = new THREE.LineBasicMaterial({color: 0xffffff});

                    var ellipse = new THREE.Line(geometry, material);
                    ellipse.rotation.x = 1.5708;
                    scene.add(ellipse);
                }

            }

        </script>

A: Cast a ray from your camera to a point where your mouse is. Then check closest distance from that ray to the middle of you solar system using distanceToPoint function. The length of output vector will be the radius of a sphere to which your ray is tangent. Using this length you can determine how close you are to a sphere that is an orbit and if it should be selected. Here's some pseudo code of that check:
var length = getDistanceToCenter(...);
var closestSphere = _(orbits).min(function(orbit) { return Math.abs(length - orbit.radius); });
if (Math.abs(closestSphere.radius - length) < EPSILON) {
    selectOrbit(closestSphere);
}


text:
Q: where does downcasted object point to? public class Animal{

    int n = 5;

    public static void main(String[] args) {

        Animal a = new Animal();
        Animal ah = new Horse();
        Horse h = new Horse();

        System.out.println(h.n); // prints 7
        System.out.println(ah.n); // prints 5
        h = (Horse) ah;
        System.out.println(h.n); // prints 7

    }
}

class Horse extends Animal{

    int n = 7;

}

My question:
Why does h.n still print 7 after h = (Horse) ah? After the assignment it should point to the same object that ah points and the n field points to 5?

A: First, let's call the field n of the class Animal "Animal.n" to avoid confusion.
Fields, unlike methods, are not subject to overriding. So in your Horse class, where you may think you are overriding the value of Animal.n with 7, you are actually declaring a new variable called n (let's call it Horse.n to avoid confusion).
So really, you have a class called Horse with two fields: Animal.n and Horse.n. Which field you get when you say "n" depends upon the static type of the variable at the time.
When you have an object whose type is Horse, but upcast to an Animal, the n field refers to Animal.n, and has a value of "5". Hence ah.n is "5".
When you have the same object, downcast again to a Horse, the n field refers to Horse.n, and has a value of "7". Hence h.n is "7".
To clarify: Indeed, h does point to the same object that ah points to -- downcasting does not change what object is being pointed at. However, the static type does affect which field of the object is being requested.

A: Every object you create (called an instance) in Java points to the class from which it was created. This is the true type of the object and doesn't change when you cast a reference to it. Similarly, every variable that references an object has a declared type. This is how the compiler will treat the object and determines what operations are allowed.
However, these two types are only loosely coupled. Casting object references changes only the declared type. It doesn't affect how the object behaves--only how the compiler treats it.


text:
Q: Is there a way to combine CMD command and Git Bash command into one alias I have been trying to combine "clear" and "git status" as one command into one git alias. Is there a way to achieve this??
I have tried the following :
git config --global alias.clearall 'clear && git status'

and also the same using nano ~/.bashrc and add the same alias.
But both don't work. So can anyone suggest another idea ?

A: Notice in git config you write git commands only for example:

git config --global alias.chst '!git checkout && git status'

Call alias command with git + aliasNAME:

git chst

For more information view this link
But you can alias from ~/.bashrc open ~/.bashrc  with any editor that you have for example nano ~/.bashrc and write alias it:

alias clearall="clear && git status"

Call it this command from git bash by writing alias name:

clearall


text:
Q: How to find distance metrics in python This is the array.
arr=[1,2,2,1,5,1]

i need to calculate the abs value of index differences between in and all the other elements if the same value, like explained below.
distance metric for a[0] = |0-3|+|0-5|=8
distance metric for a[1] = |1-2|=1
distance metric for a[2] = |2-1|=1
distance metric for a[3] = |3-0|+|3-5|=5
distance metric for a[4] = 0
distance metric for a[5] = |5-0|+|5-3|=7

output is
[8,1,1,5,0,7]

can someone help in coding this in python.

A: You can use this working example:
arr=[1,2,2,1,5,1]
res = []
for i, n in enumerate(arr):
    val = 0
    occur = [j for j, x in enumerate(arr) if x == n and j != i]
    for o in occur:
        val += abs(i-o)
    res.append(val)
print(res)

[8, 1, 1, 5, 0, 7]

a bit more efficient version with a complexity of O(n**2)
arr=[1,2,2,1,5,1]
res = []
for i, n in enumerate(arr):
    val = 0
    for j, x in enumerate(arr):
        if x == n and j != i:
            val += abs(i-j)
    res.append(val)
print(res)

A: Using list comprehensions and avoiding intermediate variables
arr = [1, 2, 2, 1, 5, 1]

output = []
for index in range(len(arr)):
    output.append(sum(abs(index - k) if arr[k] == arr[index] else 0 for k in range(len(arr))))

print(output)


text:
Q: Inverse of operator is not continuous in Banach spaces Let $X$ be a Banach space. If $A:X\to X$ is an invertible bounded operator (injective,  surjective and continuous), then $A^{-1}$ is also bounded. Now can I have an example of an unbounded operator $A:D(A)\to X$ which is invertible but $A^{-1}:X\to D(A)$ is not bounded ?

A: See the MathOverflow question https://mathoverflow.net/questions/5303/basis-of-linfinity to learn why it is consistent with ZF (without the axiom of choice) that there is no such operator.
Discontinuous everywhere defined operators can be defined using Hamel bases.  In particular, as Daniel Fischer points out, one can use a Hamel basis for $X$ to define discontinuous linear bijections $X\to X$ that answer your question.  All you really need is to define a discontinuous injective linear map $B$ on $X$, then take $A=B^{-1}$ on $B(X)=D(A)$.


text:
Q: Display a different "object" when each jQuery Galleria image loads I'm looking for a way to trigger for a different function on each individual image. I'm using the Galleria Jquery plugin and have it set up on my site. The problem is i want to display a div with information depending on which image is loaded. I can't figure out how to capture which image is displayed and how to create a condition based on it.

A: I'm not very familiar with that plug-in, but if your images are being pulled from a database, you could associate either a set range of data (like categories) or specific data per each item (like, say, a caption) with each of the images, so when they're pulled over, you can have jQuery extrapolate that data into your plug-in.

A: There's an "onImage" callback, and it's passed the image element being displayed. If you give each image an "id" value, or if you just look at the "src" attribute, then you can know what information to display.

A:
UPDATED

DEMO: http://jsbin.com/egavo/6
without hacking the original Galleria plugin, just adding this into your code!
CSS PART:
    /* HOVER CSS EFFECT */

.imageteaser {
  margin: 0;
  overflow: hidden;
  float: left;
  position: relative;
}

.imageteaser:hover {
  cursor: pointer;
}

.imageteaser .more {
  position: absolute;
  right: 20px;
  bottom: 20px;
  font-size: 1.2em;
  color: #fff;
  background: #000;
  padding: 5px 10px;
  filter:alpha(opacity=65);
  opacity:.65;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=65)"; /*--IE 8 Transparency--*/
}
.imageteaser  .desc {  display: none; }
.imageteaser:hover .more { visibility: hidden;}
.imageteaser:hover .desc{
  display: block;
  font-size: 1.2em;
  background: #111;
  filter:alpha(opacity=75);
  opacity:.75;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)"; /*--IE 8 Transparency--*/
  color: #fff;
  position: absolute;
  bottom: 11px;
  left: 0;
  padding: 10px 5px;
  margin: 0;
  width: 702px;
  border-top: 1px solid #999;
  text-align:left
}

  .imageteaser:hover .desc strong {
  display: block;
  margin-bottom: 5px;
  font-size:1.5em;
        float:right;
        margin-right:20px
}

JQUERY ( Latest Version ) PART:
$(".gallery_demo_unstyled img").click( function() {

  var src = $(this).attr('src');

  $('.imageteaser').remove();

  $('.galleria_wrapper').before('
'+
  ''+
  '> read more' +
  ''+
  'click'+
  $(this).attr('title') +
  '
');

  $('.galleria_wrapper').attr('style','display:none');

}).filter(':first').click();

   $(".imageteaser .desc strong").live( 'click' , function() {
     alert('run function!');
   });

This Do exactly what you want! ;-)
let me know!


text:
Q: After power outage, main user logs out before I can use it (16.04) My 16.04 LTS system is configured with two users: me and a (non-admin) friend. After a recent neighborhood power outage, my user logs out before I can do anything. That is, I get the login (password) prompt and supply the correct password. Screen clears, top bar (indicator) appears with expected icons, unity launcher(?) bar appears with correct icons and hides. Then there's a "flash" (screen goes white for an instant then back to normal), then back to login screen. Once the top bar is visible, I can pull down menus etc, but don't have time for anything actually happen (e.g., if I select Thunderbird).
The other user logs in just fine. Guest session logs in just fine. I can log in to terminal (Ctrl-Alt-F1) as me just fine (as well as su to me from other logins). If I try to switch to me from other user or guest, it's the same as logging in normally (as described above).

A: Yeah, nevermind. I removed ~/.auth (well, I hid them in a new directory) and afterwards I could login just fine. I just didn't think I'd get this far if there was an authority issue. And somehow I missed the line in lightdm.log that reported authorization failure. Sorry to waste your time. :(


text:
Q: Use an object as a blueprint for other objects I have created a simple object that want to use as a blueprint for other objects. But something is not going well. Can anyone find out why? When I click one button it should change innerHTML of the div to display the properties of the new objects!
here is a fiddle
var objekt = {
    name : "olsi",
    surname : "Angjellari",
    kot : function () {
        return this.name + this.surname
    },
    print : function () {
        id.innerHTML = this.kot()
    }
};

http://jsfiddle.net/cTRuL/

A: There are a number of problems:
When you want to do:
var dana = new objekt();

Then, objekt must be a function, not just an object because an object is not a constructor, only a function can be a constructor.  This is one way to do that:
function objekt() {
    this.name = "olsi";
    this.surname = "Angjellari";
};

objekt.prototype =  {
    kot : function () {
        return this.name + this.surname
    },
    print : function () {
        id.innerHTML = this.kot()
    }
};

Second, in your jsFiddle if you're going to put function names in the HTML, then those functions have to be global.  To make your code global in the jsFiddle, you have to set the upper left setting to "No wrap - in <body>" or "No wrap - in <head>".  As you had your jsFiddle, your code was defined inside an onload handler and therefore NOT reachable by function calls from your HTML.

Third, once you make objekt into a function to fix the previous issue, then you can't call objekt.print() directly.  You probably want to call .print on an actual object of type objekt like dana or boi.
You can see it all working here: http://jsfiddle.net/jfriend00/7TbEx/

A: you want to create a constructor so you can make instances using the new operator like you are trying
function objekt(name,surname){
   this.name = name||"olsi";
   this.surname = surname||"Angjellari";
   this.kot = function () {
      return this.name + this.surname
   };
   this.print = function () {
      id.innerHTML = this.kot()
   };
}

var obj = new objekt();
var obj2 = new objekt("First","Last");
obj.print();
obj2.print();

You could also make these through the prototype
function objekt(){}
objekt.prototype.name = "";
objekt.prototype.surname = "";
objekt.prototype.kot = function(){
   return this.name + this.surname;
};
objekt.prototype.kot = function(){
   id.innerHTML = this.kot();
};

var obj = new objekt();
obj.name = "First";
obj.surname = "Last";

var obj2 = new objekt();
obj2.name = "Last";
obj2.surname = "First";

obj.print();
obj2.print();


text:
Q: With function not working to load has many relation data laravel Model Eloquent I have these two model.
This phone model is a common model which can be used to save and fetch the phone value for a user, customer, Employee and so on. So the meta_value is used to save the id of related model and meta_key is used to determine the model name relation.
/* Customer Model*/
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Customer extends Model {
    /**
     * Get the Phone List.
     */
    public function phones(){
        return $this->hasMany('App\Phone','meta_value', 'id')
                    ->select('id as phone_id','contact_number as phone','contact_number','country_code','type','dial_code')
                    ->where('meta_key','customer');
    }
}
/* Phone Model*/
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Phone extends Model {
    /**
     * Get the customer that owns the phone.
     */
    public function customer(){
        return $this->belongsTo('App\Customer', 'meta_value');
    }
}

I can't get the data of phones with customer data. It always returns
[relations:protected] => Array
    (
        [phones] => Illuminate\Database\Eloquent\Collection Object
            (
                [items:protected] => Array
                    (
                    )

            )

    )

In My controller I do the following code.
/*This is the case when I want to get the data for a single customer.*/
        $customer = Customer::find('448')->with('phones')->get();
        print_r($customer); // It will return all customers with no phones value.

        $customer = Customer::find('448');
        print_r($customer);die; // It will return a single customer whose id is 448 with no phones value.

        print_r($customer->phones);die; // I can get the values of phones by this

        $customer = Customer::find('448')->with('phones');
        print_r($customer);die; // It will crash my postman when i hit this.

        /*This is the case when I want to get the data for multiple customers.*/
        $customers = Customer::where('id', '>', '447')->with('phones')->get();
        print_r($customers);die; // It will return multiple customer with empty phones value.

        // However when I iterate through the loop and get phones then I can get the phone value.
        $customers = Customer::where('id', '>', '447')->get();
        foreach ($customers as $customer) {
            $customer->phones = $customer->phones;
        }
        print_r($customers);die;

Only the iteration is working but I think that is not a good solution. Even I try load function but not working.

A: You have to select the required foreign key column meta_value:
->select('id as phone_id','contact_number as phone','contact_number','country_code',
    'type','dial_code','meta_value')

For a single customer you don't need eager loading:
$customer = Customer::find(448);
$phones = $customer->phones;

It also looks like you should use polymorphic relationships.

A: Although I suspect that selecting the phone_id as id may have affected query from checking the relationship but a quick debug would be to remove this from the related function:
->select('id as phone_id','contact_number as phone','contact_number','country_code','type','dial_code')
                ->where('meta_key','customer');

And let the function phones be simply,
public function phones(){
    return $this->hasMany('App\Phone','meta_value', 'id');
}

~UPDATED~
Then, you need to use load instead.
If you need to further do a check later on the relationship, then pass a callback to filter it:
$customer = Customer::find('448')->load(['phones' => function($query) {
    $query->where('meta_key','customer');
}]);

Or:
$customer = Customer::with(['phones' => function($query) {
    $query->where('meta_key','customer');
}])->find('448');

The initial problem is:
Using with and get on the result of the find creates another instance of the model for a fresh query hence you'll only get all the records of customer. You can use the load method, or if you'll use with then you'll have to set the filter at the end of the query functions.
For better understanding please check Laravel documentation on Eager Loading


text:
Q: BitmapData.Stride versus GetPixelFormatSize(BitmapData.PixelFormat) divided by 8 While trying to better understand all the properties of Bitmap and locked bits, I created a 10x1px image,  with the following properties:
Pixel format:Format24bppRgb

Specifies that the format is 24 bits per pixel; 8 bits each are used for the red, green, and blue components.

Color depth in bits: 24 (3 bytes)
So that means I got 10 pixels that each need 3 bytes which means I need to create a byte array of length 30 to copy in all the image data using:
Marshal.Copy(lockedBitmapData.Scan0, bytesArray, 0, 30);

The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary.

Does that mean that when I access BitmapData.Stride, it will always return an integer as if the PixelFormat was one of the 32bit variations?
Why the code below causes 2 additional bytes that are 0, instead of 10 that are 0? Or is it 2 because it is rounding up 30 bytes to 32 as the closest byte length that is divisible by 4 as the doc says? I think I misunderstood documentation and expected it to count 4 bytes for every pixel when calculating stride.
byte[] bytesArray = new byte[lockedBitmapData.Stride];
Marshal.Copy(lockedBitmapData.Scan0, bytesArray, 0, lockedBitmapData.Stride);

A: Stride is understood to be the distance from line to line, not from pixel to pixel. The difference to the expected pixels_per_line * bytes_per_pixel is due to the padding at the end of each logical line. Thus your second interpretation is mostly correct,

32 as the closest byte length that is divisible by 4 as the doc says

I would just add "are padded to ensure complete 4-byte boundaries" since 16 and 24 are as well divisible by 4. This article contains a picture, this answer contains supplementary information.
The underlying reason is hardware related. If a 2-D data structure is memory-aligned (as in this case, DWORD aligned), lookups (indexing) and bulk operations on that data run significantly faster.


text: Q: How can we configure VS2012 to auto format  and  elements used in Angularjs-ui? We have tried on two machines now to set up VS2012 to recognize the <tabset> and <tab> elements. If we wrote our own directives we would probably need to get it to recognize others.  We go to the formatting /validation menu. Set up everything but then when we try to format the code it still does not seem to recognize the new elements we added. Are we missing something. Has it been done by others ?


text:
Q: groupby + apply results in a series appearing both in index and column - how to prevent it? I've got a following data frame:
dict1 = {'id': {0: 11, 1: 12, 2: 13, 3: 14, 4: 15, 5: 16, 6: 19, 7: 18, 8: 17},
 'var1': {0: 20.272108843537413,
  1: 21.088435374149658,
  2: 20.68027210884354,
  3: 23.945578231292515,
  4: 22.857142857142854,
  5: 21.496598639455787,
  6: 39.18367346938776,
  7: 36.46258503401361,
  8: 34.965986394557824},
 'var2': {0: 27.731092436974773,
  1: 43.907563025210074,
  2: 55.67226890756303,
  3: 62.81512605042017,
  4: 71.63865546218487,
  5: 83.40336134453781,
  6: 43.48739495798319,
  7: 59.243697478991606,
  8: 67.22689075630252},
 'var3': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2}}
ex = pd.DataFrame(dict1).set_index('id')

I wanted to sort with within groups according to var1, so I wrote the following:
ex.groupby('var3').apply(lambda x: x.sort_values('var1'))

However, it results in a data frame which has var3 both in index and in column. How to prevent that and leave it only in a column?

A: You could use:
df_sorted=ex.groupby('var3').apply(lambda x: x.sort_values('var1')).reset_index(drop='var3')
print(df_sorted)

        var1       var2  var3
0  20.272109  27.731092     1
1  20.680272  55.672269     1
2  21.088435  43.907563     1
3  21.496599  83.403361     1
4  22.857143  71.638655     1
5  23.945578  62.815126     1
6  34.965986  67.226891     2
7  36.462585  59.243697     2
8  39.183673  43.487395     2

But you only need DataFrame.sort_values
sorting first by var3 and then by var1:
df_sort=ex.sort_values(['var3','var1'])
print(df_sort)

         var1       var2  var3
id
11  20.272109  27.731092     1
13  20.680272  55.672269     1
12  21.088435  43.907563     1
16  21.496599  83.403361     1
15  22.857143  71.638655     1
14  23.945578  62.815126     1
17  34.965986  67.226891     2
18  36.462585  59.243697     2
19  39.183673  43.487395     2

A: Add optional param to groupby as_index=False
ex.groupby('var3', as_index=False) \
  .apply(lambda x: x.sort_values('var1'))

Or, if you don't want multiIndex
ex.groupby('var3', as_index=False) \
  .apply(lambda x: x.sort_values('var1')) \
  .reset_index(level=0, drop=True)


text:
Q: http 500 error on first visit only The first time I visit a site I get a 500 - Internal server error. When I hit reload the site works just fine and will continue to work. If I open a different browser or close and reopen the current browser the process repeats.
http://motherscarehawaii.teamvision.biz/
The server is running IIS7.5 on windows server 2008 R2 + sp1 and this is one of many virtual hosts on the server, all others are working fine.
I see HTTP/1.1 GET / 503 32 Disabled motherscarehawaii.teamvision.biz listed in C:\Windows\System32\LogFiles\HTTPERR\httperr1.log but not sure what is disabled. The application pool is setup to run with .Net Framework v2.0.50727 in Classic mode.
Any idea's whats causing the error and how to fix it?

A: It's something to do with session cookies and how the site handles them.
First pass, no session cookie at my end,
$ wget --load-cookies cookies --save-cookies cookies --keep-session-cookies -S http://motherscarehawaii.teamvision.biz/
--2011-07-21 21:37:05--  http://motherscarehawaii.teamvision.biz/
Resolving motherscarehawaii.teamvision.biz (motherscarehawaii.teamvision.biz)... 206.72.120.169
Connecting to motherscarehawaii.teamvision.biz (motherscarehawaii.teamvision.biz)|206.72.120.169|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 500 Internal Server Error
  Cache-Control: private
  Content-Type: text/html
  Server: Microsoft-IIS/7.5
  Set-Cookie: ASPSESSIONIDASCRDQBC=GAONOAEADFONKBABDHPPMCLG; path=/
  X-Powered-By: ASP.NET
  Date: Thu, 21 Jul 2011 20:36:51 GMT
  Connection: keep-alive
  Content-Length: 1208
2011-07-21 21:37:05 ERROR 500: Internal Server Error.

second pass, now loads the cookie from the file,
$ wget --load-cookies cookies --save-cookies cookies --keep-session-cookies -S http://motherscarehawaii.teamvision.biz/
--2011-07-21 21:37:06--  http://motherscarehawaii.teamvision.biz/
Resolving motherscarehawaii.teamvision.biz (motherscarehawaii.teamvision.biz)... 206.72.120.169
Connecting to motherscarehawaii.teamvision.biz (motherscarehawaii.teamvision.biz)|206.72.120.169|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Cache-Control: private
  Content-Length: 2843
  Content-Type: text/html
  Server: Microsoft-IIS/7.5
  X-Powered-By: ASP.NET
  Date: Thu, 21 Jul 2011 20:36:53 GMT
  Connection: keep-alive
Length: 2843 (2.8K) [text/html]
Saving to: `index.html'

100%[=======================================================================================================>] 2,843       --.-K/s   in 0.1s

2011-07-21 21:37:07 (24.1 KB/s) - `index.html' saved [2843/2843]

I hope that helps you track it down further.

A: We were having the same issue on a newly created IIS 10 Server.  One of our practices is to create a specific folder tree on a separate drive (using Windows File Explorer) and then creating the application folders in that folder tree.  Because they are created outside of IIS they did not have the normal security setting for IIS_IUSRS.  The fix for us was to go to the root folder of the folder tree on that drive and add the IIS_IUSRS group and grant that group "Read & execute", "List folder contents",  "Read", and "Write" permissions.  Problem solved.


text:
Q: How do I notify fellow developers that a target function is DEPRECATED and to offer a solution? Scenario:  A cocoaPod (or any shared code/framework) has a deprecated function (in my case MD5 hash) from which I want to display a warning & solution: SHA256().
I only have access to a shared POD. I want future users to be notified that their current API (MD5) has been deprecated and hence, should use a newer API (SHA256).
How do I notify user that the following 'doOldStuff(x: Sting)' is Deprecated, an to use 'doNewStuff(x:String) instead?

I would like to display a compiler WARNING.

A: Swift
Use @available like this.
@available(*, deprecated, message: "Use doNewStuff(x:) instead")
func doOldStuff(x: String) { }

Objective-C
-(void)doOldStuffWithX:(NSString *)x __attribute__((deprecated("Use doNewStuffWithX: instead")));


text:
Q: convert null values corresponding to an Array to empty array in nifi jolt I want to achieve following JSON transformation using Jolt processor in NIFI
By focusing on values field, in the first input in json (id 900551), values are populated as the following
input JSON
{
    "id": 900551,
    "internal_name": [],
    "values": [
        {
            "id": 1430156,
            "form_field_id": 900551,
            "pos": 0,
            "weight": null,
            "category": null,
            "created_at": "2020-10-15 12:55:02",
            "updated_at": "2020-11-27 10:45:09",
            "deleted_at": null,
            "settings": {
                "image": "myimage.png"
                "fix": false,
                "bold": false,
                "exclusive": false
            },
            "internal_value": "494699DV7271000,6343060SX0W1000,619740BWR0W1000",
            "css_class": null,
            "value": "DIFFERENCE",
            "settings_lang": {},
            "value_html": ""
        }
    ]
}

On the second input Json file to parse, values is null.
{
    "id": 900552,
    "internal_name": [],
    "values": []
}

I would like to convert null values to an empty array in my conversion
Is there a way to do this using existing Jolt operations ?
Thanks.

A: The default operation is what you are looking for:

Defaultr walks the spec and asks "Does this exist in the data?  If not, add it."

In our case:

if the value for "values" key is null, put the empty array instead

Here is the spec:
[
  {
    "operation": "default",
    "spec": {
      "values": []
    }
  }
]

tested with https://jolt-demo.appspot.com/

edit: answering the question from the comment:
Maybe this workaround will work for you


text:
Q: android.database.sqlite.SQLiteException: no such column: while compiling: UPDATE I am trying to update some columns in a row in SQLite in an Android app, however I am stuck at this error which I just don't know where it comes from.
android.database.sqlite.SQLiteException: no such column: location (code 1): , while compiling: UPDATE user SET email=?,location=?,mobile=? WHERE id=?

This is the code I use to update info:
public void updateUserInfo(String mobile, String email, String location) {
    SQLiteDatabase db = this.getWritableDatabase();

    String[] tablei = new String[1];
    tablei[0] = "1";

    ContentValues values = new ContentValues();
    values.put(KEY_MOBILE, mobile); // Mobile
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_LOCATION, location); // Location

    // Inserting Row
    //long id = db.update().insert(TABLE_USER, null, values);
    long id = db.update(TABLE_USER, values, "id=?", tablei);
    db.close(); // Closing database connection

    Log.d(TAG, "Info of user updated in sqlite: " + id);
}

This is my table in which there are all the columns used:
   private static final String KEY_ID = "id";
   private static final String KEY_LOCATION = "location";
                          .....

    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE," + KEY_APIKEY + " TEXT,"
            + KEY_MOBILE + " TEXT," + KEY_LOCATION + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";

Thank you in advance for your help !

A: I think you modified the database scheme after the first install of the app.
You have to write an update script from the old version of the Database to the new version. (ALTER TABLE tablename ADD COLUMN ....)
Or delete and install the app again.


text:
Q: Python Telnetlib read_until '#' or '>', multiple string determination? if (tn.read_until('>')):
    action1
else:
    action2

or
if (tn.read_until() == '>'):
    action1
else:
    action2

I just want the read_until() to check which desired String comes first, and do different actions.
Or is there any equivalent ways?

A: Look at the docs. Read until wants the expected string as a positional argument and an optional timeout. I would do it like this:
>>> try:
...     response = tn.read_until(">", timeout=120) #or whatever timeout you choose.
... except EOFError as e:
...     print "Connection closed: %s" % e

>>> if ">" in response:
...    action1
... else:
...    action2

If you want multiple different characters you can use read_some()
>>> while True: #really you should set some sort of a timeout here.
...    r = tn.read_some()
...    if any(x in r for x in ["#", ">"]):
...        break

A: Better yet just use:
buff_tpl = tn.expect(["#", ">"])

This will return a tuple with three items, the first (index of 0) is the index of the list item matched, the second is and object matched, and the third is the output text.
You can print the buffer output using buff_tpl[2], and know which item matched using buff_tpl[0]


text:
Q: grails resource tags creating duplicate app context in link At times, our code has a need to create links for resources.  When this happens,  it looks like the following:
<link rel="stylesheet" type="text/css"
href="${resource(dir: '/css/', file: 'UXdashboard-pdf.css') }"
media="all"/>

However, this creates a link that looks like the following (note the duplicate app context)
<link href="/ici/ici/css/UXdashboard-pdf.css" media="all"

We do not have grails.serverUrl or grails.app.context defined. We do have app.name='ici' set in application.properties.
We deploy using tomcat set up with autodeploy="true" which should create an application context of 'ici' based on the war file name.
I am not sure where the second app-context is coming from. Should I not be setting app.name in application.properties?  I could specify the 'base' parameter, but I would prefer to understand exactly where the duplicate context is coming from before I try to work around it.
We use apache as our front end document server, and apache seems to be able to handle these links as I see 200 codes returned for them.  But we have a plugin that does pdf generation, and I suspect that it is not finding the css file because of the link.
thanks!

A: I'm actually answering my own question in case someone else runs into this situation.  It turns out that the double /<appcontext>/<appcontext>  is caused by grails.resources.uri.prefix ="ici".
We also use the Resources plugin, which is integrated with the g:resource tag.  The resources plugin automatically adds a /static/ directory when forming its urls. We don't use a static subdirectory and grails.resources.uri.prefix allows one to override it.  Just setting it to the empty string didn't work, but apache can handle the <appcontext>/<appcontext>.  So all I need to do in the pdf generation case is rewrite this one link.


text:
Q: Lock-Up with Gesture Input I'm using MonoTouch in Xamarin Studio to read gestures in my MonoGame. I've added the following section of code to read gestures.
while(TouchPanel.IsGestureAvailable)
{
    GestureSample sample = TouchPanel.ReadGesture();
}

The following was added at the start of the program:
        TouchPanel.EnabledGestures = GestureType.Tap |
                                     GestureType.Hold |
                                     GestureType.None;

But when I touch the screen on the simulator or on the device, it completely locks up and becomes non-responsiveness to debugging.
What could cause this lock-up? Have I missed something in my code?

A: Your loop above will run forever. It needs to be an if-statement.
I'm assuming this is MonoGame you're using, but IsGestureAvailable will always return the same value within an Update() cycle of your Game class.


text:
Q: Javascript: make rectangle grow upwards I'm trying to create a code that has a bar rise while a certain condition is met, and if not, it falls back down. I figured the best way to do this is to increment the height and margin-top inversely so that as the margin-top decreases, the height can increase, creating the illusion that the bar was only ever rising. However, it seems that the top of the bar is stuck and changing the margin-top doesn't change anything. Here's my code:
function progresMove() {
    if (playerMargin >= marginRange[0] && playerMargin <= marginRange[1]) {
        progressHeight += .75;
        progressMargin -= .75;
        progress.style.cssText = "margin-top: " + progressMargin + "px";
        progress.style.cssText = "height: " + progressHeight + "px";
    } else {
        progressHeight -= 1.5;
        progressMargin += 1.5;
        progress.style.cssText = "margin-top: " + progressMargin + "px";
        progress.style.cssText = "height: " + progressHeight + "px";
    }
}

This function is called every .05 seconds, and acts upon already created HTML elements with some styling:
width: 24px;
    background-color: #64DD17;
    margin-left: 3px;
    display: block;

All it does at the moment is push the rectangle down.
Also, it is inside a div within a div if that makes a difference. I've tried floating them, putting them in inline-block, and having overflow be hidden, and it doesn't make a difference.
Thanks for the help!

A: Give the parent position: relative and the element itself position: absolute and bottom: 0. That way the element is always aligned with the bottom of the parent. But you have to specify height and width of the parent in some way, otherwise it will collapse if the children are positioned absolutely.

A: Replace cssText:
progress.style.cssText = "margin-top: " + progressMargin + "px";
progress.style.cssText = "height: " + progressHeight + "px";

with:
progress.style.marginTop = progressMargin + "px";
progress.style.height = progressHeight + "px";

Explanation:
You're overwriting cssText value, so there's no rule for margin-top at the end of your function.
Consider following snippet:

div1.style.cssText = "color: red";
div1.style.cssText = "background-color: yellow";

div2.style.cssText = "color: yellow";
div2.style.cssText += ";background-color: red";

div3.style.color = "red";
div3.style.backgroundColor = "yellow";

div 1

div 2

div 3

First div's background becomes yellow, but text is still black. In second and third div both changes are applied


text:
Q: full CSS parallax site not working on chrome I am working on my website using the effects done in here: http://keithclark.co.uk/articles/pure-css-parallax-websites/ Everything works fine except in chrome, and I have no idea why. Can someone please educate me where the issue is? Here is my webpage: http://emmanuelmelendez.com.mx/home.html Thanks!
HTML

 Inicio

Acerca de

Portafolio

Contacto

            <video autoplay loop poster="img/bg/Logo.jpg" class="background">
                <source src="video/bg/IntroReel.webm" type="video/webm">
                <source src="video/bg/IntroReel.mp4" type="video/mpeg">
            </video>

Bienvenidos a mi sitio

            Ver Demo Reel

Producciones

            <video autoplay loop poster="img/bg/video.jpg" class="background">
                <source src="video/bg/fondoVideo.webm" type="video/webm" >
                <source src="video/bg/fondoVideo.mp4" type="video/mpeg">
            </video>

Audiovisual

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta sed odio eget facilisis. Aliquam diam eros, posuere et hendrerit sed, pharetra pretium lorem. Praesent sodales risus neque, a vulputate libero pretium sit amet. Donec sapien nunc, eleifend vitae pellentesque ac, lobortis a eros. Aenean fringilla odio sit amet laoreet semper. Donec ut dapibus magna. Sed eu porta purus. Duis lorem mauris, elementum semper sodales in, tincidunt vel nibh.

Desarrollo Web

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta sed odio eget facilisis. Aliquam diam eros, posuere et hendrerit sed, pharetra pretium lorem. Praesent sodales risus neque, a vulputate libero pretium sit amet. Donec sapien nunc, eleifend vitae pellentesque ac, lobortis a eros. Aenean fringilla odio sit amet laoreet semper. Donec ut dapibus magna. Sed eu porta purus. Duis lorem mauris, elementum semper sodales in, tincidunt vel nibh.

Fotografía

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta sed odio eget facilisis. Aliquam diam eros, posuere et hendrerit sed, pharetra pretium lorem. Praesent sodales risus neque, a vulputate libero pretium sit amet. Donec sapien nunc, eleifend vitae pellentesque ac, lobortis a eros. Aenean fringilla odio sit amet laoreet semper. Donec ut dapibus magna. Sed eu porta purus. Duis lorem mauris, elementum semper sodales in, tincidunt vel nibh.

Sígueme en mis redes sociales

        Instagram

        500px

 Emmanuel Melendez ©

CSS

body{
    background: white;
    font-family: Light, Fallback, helvetica;
    color: white;
    font-size: 21px;
    overflow: hidden;
    text-align: center;
}
    h1{
        margin-top: 35vh;
        background: rgba(0,0,0,.6);
        padding: 10px;
        font-family: Titulo,Fallback, helvetica;
        font-size: 90px;
    }

    h2{
        margin-top: 25vh;
        background: rgba(0,0,0,.6);
        padding: 10px;
        font-family: Titulo,Fallback, helvetica;
        font-size: 90px;
    }

    h3{
        margin-top: 15vh;
        background: rgba(0,0,0,.6);
        padding: 10px;
        font-family: Titulo,Fallback, helvetica;
        font-size: 60px;
    }

    p{
        width: 960px;
        margin: 0 auto;
        padding: 16px;
        text-align: justify;
        background: rgba(0,0,0,0.6);
    }

/* !PC */
@media all and (min-width:600px) {
/* Menu */
    header{
        background: white;
        height: 44px;
        font-family: Menu, Fallback, Helvetica;
        width: 100%;
        border-bottom: 1px solid #b31219;
    }

    header ul{
        width: 960px;
        padding-left: 20px;
        margin: 0 auto;
        list-style-type: none;
        color: black;
    }

    header li{
        display: table-cell;
        vertical-align: middle;
        padding-top: 11px;
    }

    header li a{
        padding: 12px 40px;
        text-decoration: none;
        color: black;
    }

    header li a:hover{
        background: black;
        color: white;
    }

/* Parallax */
    .parallax {
        height: 500px; /* fallback for older browsers */
        height: 100vh;
        overflow-x: hidden;
        overflow-y: auto;
        -webkit-perspective: 300px;
        perspective: 300px;
     }

    .parallax__group {
        position: relative;
        height: 100vh;
        width: 100vw;
        -webkit-transform-style: -webkit-preserve-3d;
        transform-style: preserve-3d;
    }

    .parallax__layer{
        position: absolute;
        overflow: visible;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

    .parallax__base {
        -webkit-transform: translateZ(0);
        transform: translateZ(0);
        z-index: 2;
    }

    .parallax__back {
        -webkit-transform: translateZ(-300px) scale(2);
        transform: translateZ(-300px) scale(2);
        z-index: 1;
    }
 /* !Reel */
    #reel a{
        text-decoration: none;
        color: white;
        font-family: Titulo,Fallback, helvetica;
        font-size: 50px;
        text-align: center;
        padding: 10px 20px;
        background: #b31219;
        border-radius: 15px;
    }

    #reel a:visited{
    }

    #reel a:hover{
        background: black;
    }

    #reel a:active {
        color:black;
        background: white;
    }

/* Servicios */
    #servicio{
        background: #005280;
    }

/* Web */
    #web{
        background-image: url('/img/bg/web.jpg');
        background-position: center center;
        background-size: auto 100%;

    }
/* Fondos*/
    .background{
        /* solo usar para alinear contenido en formato full HD*/
        width: auto;
        height: 100vh;
        position: fixed;
        top: 50%;
        transform: translateX(-50%) translateY(-50%);
        z-index: -100;
    }

/* Redes */
    #redes{
        background-image: url('/img/bg/medios.jpg');
        background-size: 100% auto;
        font-size: 50px;
        font-family: Titulo, Fallback, helvetica;
    }

    #redes a{
        padding: 0px 15px;
        background: black;
        text-decoration: none;
        color: white;
    }

    #redes a:hover{
        background: white;
        color: black;
    }

/* !Copyright */
    #Copyright{
        padding-top: 6vh;
        width: 100%;
        height: 16vh;
        background: #b31219;
        color: white;
        font-size: 50px;
        font-family: Titulo, Fallback, helvetica;
        text-align: center;
    }
}

A: You should use preserve-3d instead of -webkit-preserve-3d
.parallax__group {
    position: relative;
    height: 100vh;
    width: 100vw;
    -webkit-transform-style: preserve-3d; /* <-- */
    transform-style: preserve-3d;
}


text:
Q: Как сделать, чтобы из папки выдавались все фотографии, а не случайная? img_list23 = ['img_list43/ocr.jpg', 'img_list43/ocr1.jpg', 'img_list43/ocr2.jpg']
img_path = random.choice(img_list23)
await message.answer_photo(photo=open(img_path, "rb"))

A: Рандомное фото достается из функции random.choice(img_list23), уберите ее и переберите массив
img_list23 = ['img_list43/ocr.jpg', 'img_list43/ocr1.jpg', 'img_list43/ocr2.jpg']
for image in img_list23:
    await message.answer_photo(photo=open(image, "rb"))


text:
Q: Как делают оплату через мобильные приложения? У меня есть задача сделать приложение с возможностью оплаты прямо из него, в какую сторону копать ? Если есть возможность то предоставьте ссылки на сервисы организующие подобные услуги ?
Причем оплата интересует с карты а не по смс. т.е. пользователь вводит данные карты с нее списываются деньги, далее пользователь получает подтверждение оплаты.
Пояснение:
Меня интересует Существует ли сервис который предоставляет API который можно было бы интегрировать в мое приложение. Что бы в итоге пользователь напрямую из моего приложения смог бы совершать покупки?

A: Есть сервисы такие как Payler, Робокасса, PayOnline и ряд других. Также наверняка подобные возможности могут предоставить некоторые банки.
К сожалению, в данном вопросе очень много нюансов. Поэтому конкретно подсказать что-либо сложно. Особенно при столь общей постановке вопроса. Так, что детали уже уточняйте сами в соответствующей документации или техподдержке.