Q: Composer debug dependencies I should figure out, how to debug such situations?
I try to send mail throw Mailgun package.
How to figure out why the class is not found? Error: Class 'Mailgun\Messages\MessageBuilder' not found in /vendor/boundstate/yii2-mailgun/Message.php:239
but IDE shows me that class exist in package mailgun/mailgun-php
Take a look on a slice of composer.json:
    "boundstate/yii2-mailgun": "0.0.4",
    "Mailgun/Mailgun-php": "^1.0",

ADD:
I have required autoload.php Also, composer use psr4. I see the correct path to classes. Take a look:
    'boundstate\\mailgun\\' => array($vendorDir . '/boundstate/yii2-mailgun'),
    'Mailgun\\' => array($vendorDir . '/mailgun/mailgun-php/src'),

A: Usually, such things happen when you didn't require vendor/autoload.php, or autoload wasn't generated. IDE may show you that everything is OK just because it parsed your composer.json.
Try to:

*

*composer update

*get sure you required vendor/autoload.php in your script


Q: Handling date from list of times I have a list of time.
time_list = ['7pm', '8pm', '9pm', '10pm', '11pm', '12am', '1am', '2am']

and from there a list of floats as well
fl_list = ['1.0', '0.0', '0.0', '0.0', '0.0', '0.0', '11', '12.0']

Upon inserting in the database,
I set the date of time 7pm-12am to date today, and 1am-2am to date tomorrow.
date_today = datetime.datetime.utcnow()
date_tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)

My code is like this:
has_tomorrow_record = all(any(x in y for y in time_list) for x in ["12am", "1am"])

then to get the date I have to do the below condition
for t in time_list:
    if has_tomorrow_record and "am" in t:
        if t != "12am":
            date = date_tomorrow

Is there a cleaner way to determine the dates for the time_list?


Q: Include of non-modular header inside framework module 'AppLovinSDK' - Archive only error I get this error only when I try to archive, building for simulator or other test device works. Previously, I had this problem when trying to build for a test device, but I started over and reinstalled the pod and it worked. I have tried setting 'Allow non-modular Includes in Frameworks' to yes in both my project and Target, but this has NOT worked. Any ideas on how to get out of this would be greatly appreciated!

A: I got the same error (for archiving only) for my Swift framework with C code inside.
Only this remedy helped me.
Add -Xcc -Wno-error=non-modular-include-in-framework-module in Other Swift Flags (build settings of framework). This flag forces the compiller count that error as a warning.


Q: Invalid label in mozilla firefox I've a JSP page like this with name test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
%>

{"feed": "test"}

and an html page where i use jquery for reading the json object.
    <html>
    <head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
    <script type='text/javascript'>
    $(function(){

    $.getJSON("localhost:8080/test.jsp?callback=?",{test:"test"}, function(data){alert("here");});

    })

    </script>
    </head>
    </body>
    something here
    </body>
    </html>

but it shows an error as invalid label in firefox. Can anyone explain me the reason for this error.
I've tried google but could not find a solution or explanation to my problem. What needs do be done for this. Please help me out.
Thanks

A: I've found the solution to the problem by some hit & trial.
It is because when we make getJSON() call on cross domain then response should be wrapped inside a function name. This function is our callback handler for the response in the script.eg
html file :
 <html>
    <head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
    <script type='text/javascript'>
    $(function(){
       $.getJSON("localhost:8080/test.jsp?callback=?");
    }
   function test(data){
      alert(data.feed);
    }

And the jsp test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
out.write("test({\"feed\": \"test\"})");
%>

hope if anybody has the same problemm this will help.you can pass the callback function name as a parameter and make jsp at the server such that it uses that name to wrap the response.

A: I have encountered the same issue which was actually because of the some issue with json or ajax call. In your json call it should be {"test":"test"} instead of {test:"test"}.
Try it should work if this is the issue.


Q: Importing Json field from csv to MySQL 5.7.19-0ubuntu0.16.04.1 I have MySQL table consisting of 3 columns having type of (cookie vachar, userdata json, userprefernce json). I am trying to load the data from csv but it gives the following error :
Error:
Error Code: 3140 Invalid JSON text: Invalid value at position 0 in value for column userdata'
I have tried to validate the JSON it looks fine. Now I couldn't understand what is the problem
Sample Row:
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'

A: I can't reproduce the problem:
File: /path/to/file/data.csv
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'

MySQL Command Line:
mysql> \! lsb_release --description
Description:    Ubuntu 16.04.2 LTS

mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.19    |
+-----------+
1 row in set (0.00 sec)

mysql> DROP TABLE IF EXISTS `table`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `table` (
    ->   `cookie` VARCHAR(25) NOT NULL,
    ->   `userdata` JSON NOT NULL,
    ->   `userprefernce` JSON NOT NULL
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> LOAD DATA LOCAL INFILE '/path/to/file/data.csv'
    ->   INTO TABLE `table`
    ->   FIELDS TERMINATED BY ', '
    ->          OPTIONALLY ENCLOSED BY '\''
    ->   LINES TERMINATED BY '\n';
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT
    ->   `cookie`,
    ->   `userdata`,
    ->   `userprefernce`
    -> FROM
    ->   `table`\G
*************************** 1. row ***************************
       cookie: ZwpBHCrWObHE61rSOpp9dkUfJ
     userdata: {"models": {"XC90": 1, "Grand Cherokee": 1}, "bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}}
userprefernce: {"models": "Grand Cherokee,XC90", "bodystyle": "SUV/MUV", "budgetsegment": "EP"}
1 row in set (0.00 sec)


Q: Makefile and Shell Script (Bash) What is the relationship between Makefile and Bash?
Example in Makefile you have:
CC = gcc

But if you type this in the shell, you get error:
~# CC = gcc
-bash: CC: command not found

Understandably, because there are spaces. But it works in Makefile.
Also, in Makefile you use command substitution $()
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)

which should be variable substitution $CC or ${CC} in bash.
So Makefile syntax and bash syntax are different, but they do seem related, for example $@.

A: There's no relationship - make and bash are two separate programs that parse distinct syntaxes. That they have similar or overlapping syntactic elements is likely due to having been developed around the same time and for some similar purposes, but they don't rely on the same parser or grammar.
Many distinct languages have shared language features either for ease of adoption or from imitation. Most languages use + to mean addition, for example, but that doesn't make the languages related.


Q: Python: run python script as subprocess and get the output I have a python script calculate.py with a function in it like below
def mytest():
    Y_pred = {}
    Y_pred['a'] = [1,2,3]
    Y_pred['b'] = [45,54,77]
    return Y_pred

Now from python console I want to run the python script using subprocess and get the return value `Y_pred' into a variable. So I want something like the pseudocode below from the terminal
python3
>>> import subprocess
>>> returned_val =  subprocess.call([run calculate.py here and call mytest() ])

In the end, I want the returned value of mytest() to a variable returned_val.

A: You need to do a few things.
First, in calculate.py call the mytest function, add the following at the end:
if __name__ == '__main__':
    print(mytest())

Now when you execute the calculate.py script (e.g. with python3 /path/to/calculate.py), you'll get the mytest's return value as output.
Okay, now you can use subprocess.check_output to execute the script, and get output:
returned_bin =  subprocess.check_output('/usr/bin/python3 /path/to/calculate.py'.split())

Replace the paths accordingly.
The value of returned_val would be binary string. You need to decode it to get the respective text string:
returned_val = returned_bin.decode('utf-8')  # assuming utf-8

Now, as the returned value from myfunc is a dict and in returned_val is a string,
you can use json.loads(returned_val) to get the same dict representation back.

A: subprocess.check_output
import subprocess
[ print(i) for i in subprocess.check_output(['ls']).split() ]

output, my current directory:
b'a.sh'
b'app'
b'db'
b'old.sh'


Q: Get all edges of a cuboid (3D NumPy array) Having a 3-dimensional numpy array A I want to get all the edges (imagine this array as a cuboid).
Well, A[0, 0, :] would give me one edge, A[0, -1, :] second one and A[:, -1, -1] yet another one... so all I'd have to do is get all permutations of 0, -1 and : and use them as indices. Zero and minus one are easy, but how would I do this with colon?
I can solve it the long way, but it's ugly and I bet there is some neat numpy solution to this. Something like:
for indices in permutations([0, -1, ':']):
    edge = A[indices]
    ...

What I want to do in the end is numpy.any() on the set of all edges to see if all edge-values are zero.

A: : is same as slice(None, None, None)
A[0, -1, :] is same as
obj = (0, -1, slice(None, None, None))
A[obj]


Q: Get only git diff output in tab I want to get only output of git diff of whole repository, not just a file, in a tab, Not Split With The Commit Message!
In the issues I found a:
command GdiffInTab tabedit %|Gdiff

But this one opens an split view with commit message, the thing I want is to show only git diff in new tab when editing git commit message.
Is it possible? Or should I try doing it myself, something like:
function GitDiffTab()
  exe "tab new %"
  exe "%!git diff"
  exe "se ft=diff"
endfunction

But it doesn't work when editing commit message.

A: Use :terminal (requires Vim 8.1+)
:-tab terminal git --no-pager diff

Using fugitive.vim we can create a command:
command! -bang Tdiff execute '-tab terminal ' . call(fugitive#buffer().repo().git_command, ['--no-pager', 'diff'] + (<bang>0 ? ['--cached'] : []))

Use :Tdiff to do git diff and :Tdiff! to do git diff --cached
For more help see:
:h :tab
:h :terminal


Q: SQL Query, get only the line where a value appear 4 time I've got a table Customer (ID, Ref, LastName, FirstName).
I have to bring out all lines whose reference is the same at least four times.
I tried this unsuccessfully :
SELECT * from MyTable Where (select count(ref) from MyTable Group By ref) >= 4

Of course it is wrong, but I don't know how to do this in one query.

A: You need to use HAVING clause like below
SELECT * from Customer
Where ref in (select ref from Customer Group By ref having count(*) >= 4)

SQL Demo

A: If I understand correctly, you can use the Having clause in the query:

SELECT Ref, LastName, FirstName
from MyTable
group by Ref, LastName, FirstName
having count(*) >= 4

I have omitted ID, since this is possibly a primary key and probably not required here as the grouping wouldn't work.
EDIT: Since the above query will not return your result...You can also use a join...
    SELECT  *
    FROM    Customer c
        INNER JOIN ( SELECT ref
                     FROM   Customer
                     GROUP BY ref
                     HAVING COUNT(*) >= 4
                   ) t ON c.ref = t.ref

A: SELECT * from MyTable Group By ref HAVING COUNT(*) >= 4

A: SELECT Ref, LastName, FirstName
from YourTable
group by Ref, LastName, FirstName
having count(*) >= 4

A: assuming records with the same Reference associate to the same customer then something meaningful can be got from :
select ID , max(Ref) as the_Ref , count(Ref) as count_ref  from Customer group by Ref having count(Ref) >= 4;

If , however ,  Ref refers to something which occurs independently of the existence of customers ( maybe its used to refer to customer orders ) I'd recommend you consider normalising (http://en.wikipedia.org/wiki/Database_normalization) the data model a little more into two tables instead of one viz :
Customer( ID , firstName , LastName )
Customer_Order ( Ref , Customer_ID)

whats known as a foreign key relationship can then be set up between these two tables

A: As a lover of INNER JOIN, I would prefer the following way.
SELECT *
FROM Customer C
INNER JOIN (
    SELECT Ref, LastName, FirstName, COUNT(1) AS NumberOfRef
    FROM Customer
    GROUP BY Ref, LastName, FirstName
) T ON T.Ref = C.Ref AND T.LastName = C.LastName AND T.FirstName = C.FirstName AND T.NumberOfRef >= 4

However, after I did it, I started to feel the table Customer to be a bit strange. Even though we normalize it, as @diarmuid suggested, what should we use as the primary key for Customer_Order?
Customer(ID , FirstName, LastName )
Customer_Order (Ref, CustomerID)


Q: Linq ToDictionary Not Defined? I have this code
var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .Select(zb => new
     {
         Key = zb.Key,
         GroupWiseContacts = zb.Select(x => x.Contact).ToList()
     })
    .ToDictionary<string,List<string>>(y => y.Key, y => y.GroupWiseContacts)

I don't know what is wrong with this code.
Compile time error msg says:System.Generic.IEnumerable does not contain definition of and best extension method overloads has some invalid arguments. i can see only two overloads of ToDictionary Method in my visual studio tooltip sort of documentation whereas i have come across more than two overloads of ToDictionary on the web
Edit Here is exact Error message at compile time

Error 13  'System.Collections.Generic.IEnumerable<AnonymousType#1>'
  does not contain a definition for
  'ToDictionary' and the best extension
  method overload
  'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>,
  System.Func<TSource,TKey>,
  System.Collections.Generic.IEqualityComparer<TKey>)'
  has some invalid arguments

A: The compiler message makes the error clear: There is no method ToDictionary which can accept the arguments and types specified.
The mistake here is in specifying the type arguments on ToDictionary. The MSDN documentation defines the extension method as ToDictionary<TKey, TSource>. The source in your example is IEnumerable<AnonymousType#1>, but you have specified a type of List<string>.
To correct the error, omit the type arguments; the compiler will infer the correct types. You can additionally combine the Select and ToDictionary transformations into a single statement:
var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .ToDictionary(
        y => y.Key,
        y => y.Select(x => x.Contact).ToList());

A: Rewrote your code (and added .AsEnumerable()):
var dictionary = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .AsEnumerable()
    .ToDictionary(
        i => i.Key,
        i => i.Select(x => x.Contact).ToList()
    )
);

A: Don't run that group operation in the database, it'll cause the elements of each group to be fetched in separate roundtrips.
ILookup<string, string> contacts = dr.mktDoctorContacts
  .ToLookup<Contact, string, string>(x => x.ContactType, x => x.Contact);


Q: Scaffolding feature for winforms or wpf application I'd like to build a new winforms or wpf application, in which I'd like to use the concept of scaffolding like I saw for the Asp.net mvc5 application
Introduction To Scaffolding in Visual Studio 2013 RC
I need to know if this feature exists for the desktop applications like winforms or wpf

A: It is not possible to make common code for all application. There are various type of windows application for example Database Application, Client Server Application, System Utilities, etc So, the mechanism of all applications are different then how we can define a common code template for all application. It is up to you that what you want to use Database or TcpIP Socket for your application. I know my answer is not clear. Because it is very hard to define that why we could not create scaffolding.


Q: Insert value in variable I have a really easy (maybe stupid) question. I have following code to detect aruco markers with the aruco library:
MarkerDetector MDetector;
vector<Marker> Markers;

this->TheCameraParameters.readFromXMLFile(CAMERA_PARAM_FILE);
this->TheCameraParameters.resize(frame.size());
MDetector.detect(frame,Markers, this->TheCameraParameters, MARKER_SIZE);

This code gives me a vector (Markers) that consists of different detected markers. If I print Markers out I get following:
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533

But now I want to get the pixel values of the marker. With Markers[0].id,Markers[0].Tvec,Markers[0].Rvec I can extract the id, translation and rotation matrix, but I cant find a way to get the pixel values. Can someone help me with this?

A: I found the answer after an intensive search in the library.
In following output
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533

The first element (24) is the id of the marker. The next 4 elements are the pixel coordinates of the 4 corners. With Markers[0][0].x and Markers[0][0].y you get the x- and y-coordinate of the top left corner.


Q: Dynamic string parsing in C# I'm implementing "type-independent" method for filling DataRow with values.
Intended functionality is quite straight forward - caller passes the collection of string representations of column values and DataRow that needs to be filled:
private void FillDataRow(List<ColumnTypeStringRep> rowInput, DataRow row)

ColumnTypeStringRep structure contains the string representation of value, column name, and - what's of most importance - column data type:
private struct ColumnTypeStringRep
{
    public string columnName; public Type type; public string stringRep;
    public ColumnTypeStrinRep(string columnName, Type type, string stringRep)
    {
        this.columnName = columnName; this.type = type; this.stringRep = stringRep;
    }
}

So what's that "type-independency"? Basically I don't care about the data row schema (which always be a row of some typed data table), as long as passed column names match DataRow's colum names and column data types match those of DataRow I'm fine. This function needs to be as flexible as possible (and as simple as possible - just not simpler).
Here it is (almost):
private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
Debug.Assert(rowInput.Count == row.Table.Columns.Count);

foreach (ColumnTypeStrinRep columnInput in rowInput)
{
    Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
    Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);

    // --> Now I want something more or less like below (of course the syntax is wrong) :

    /*
    row[columnInput.columnName] =  columnInput.type.Parse(columnInput.stringRep);
    */

    // --> definitely not like below (this of course would work) :

    /*
    switch (columnInput.type.ToString())
    {
        case "System.String":
            row[columnInput.columnName] = columnInput.stringRep;
            break;
        case "System.Single":
            row[columnInput.columnName] = System.Single.Parse(columnInput.stringRep);
            break;
        case "System.DateTime":
            row[columnInput.columnName] = System.DateTime.Parse(columnInput.stringRep);
            break;
        //...
        default:
            break;
    }
    */
}

}
Now You probably see my problem - I don't want to use the switch statement. It would be perfect, as in the first commented segment, to somehow use the provided column type to invoke Parse method of particular type that returns the object of that type constructed from string representation.
The switch solutions works but it's extremely non flexible - what if in future I'll be filling not the DataRow but some other custom type with "columns" that can be of custom type (of course every such type will need to expose Parse method to build itself from string representation).
Hope you got what I mean - its like "dynamic parsing" kind of functionality. Is there a way to achieve this in .NET?
Example of FillDataRow call could look like this:
List<ColumnTypeStrinRep> rowInput = new List<ColumnTypeStrinRep>();
rowInput.Add(new ColumnTypeStringRep("colName1", Type.GetType("System.Int32"), "0"));
rowInput.Add(new ColumnTypeStringRep("colName2", Type.GetType("System.Double"), "1,11"));
rowInput.Add(new ColumnTypeStringRep("colName3", Type.GetType("System.Decimal"), "2,22"));
rowInput.Add(new ColumnTypeStringRep("colName4", Type.GetType("System.String"), "test"));
rowInput.Add(new ColumnTypeStringRep("colName5", Type.GetType("System.DateTime"), "2010-01-01"));
rowInput.Add(new ColumnTypeStringRep("colName6", Type.GetType("System.Single"), "3,33"));

TestDataSet.TestTableRow newRow = this.testDataSet.TestTable.NewTestTableRow();
FillDataRow(rowInput, newRow);
this.testDataSet.TestTable.AddTestTableRow(newRow);
this.testDataSet.TestTable.AcceptChanges();

Thank You!

A: The TypeConverterclass is the generic .NET way for converting types. The System.ComponentModel namespace includes implementation for primitive types and WPF ships with some more (but I am not sure in which namespace). Further there is the static Convert class offering primitive type conversions, too. It handles some simple conversions on itself and falls back to IConvertible.

A: First off, your using a struct to pass a complex data around. That is a really bad idea. Make that a class instead.
That said, it sounds like you need a factory to create instances of a parser interface:
interface IColumnTypeParser
{
    // A stateles Parse method that takes input and returns output
    DataColumn Parse(string input);
}

class ColumnTyeParserFactory
{
    IColumnTypeParser GetParser(Type columnType)
    {
        // Implementation can be anything you want...I would recommend supporting
        // a configuration file that maps types to parsers, and use pooling or caching
        // so you are not constantly recreating instances of your parsers (make sure your
        // parser implementations are stateless to support caching/pooling and reuse)

        // Dummy implementation:
        if (columnType == typeof(string)) return new StringColumnTypeParser();
        if (columnType == typeof(float)) return new FloatColumnTypeParser();
        // ...
    }
}

Your FillDataRow implementation would hten use the factory:
m_columnTypeParserFactory = new ColumnTypeParserFactory();

private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
    foreach (ColumnTypeStrinRep columnInput in rowInput)
    {
        var parser = m_columnTypeParserFactory.GetParser(columnInput.type);
        row[columnInput.columnName] parser.Parse(columnInput.stringRep);
    }
}

A: In short there is nothing like that - no automagical conversion. You have to specify conversion yourselves. That said
static class Converters{
    static Dictionary<Type, Func<string, object>> Converters = new ...

    static Converters{
        Converters.Add(typeof(string), input => input);
        Converters.Add(typeof(int), input => int.Parse(input));
        Converters.Add(typeof(double), double => double.Parse(input));
    }
}

void FillDataRow(IList<string> rowInput, row){
    for(int i = 0; i < rowInput.Length; i++){
       var converter = Converters.Converters[Column[i].DataType];
       row[i] = converter(rowInput[i])
    }
}

A: How about Convert.ChangeType?
You might consider something fancy with generics btw.
foreach (ColumnTypeStrinRep columnInput in rowInput)
{
    Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
    Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);
    ...
    row[columnInput.columnName] = Convert.ChangeType(columnInput.stringRep, columnInput.type);
}

More on Convert.ChangeType:
http://msdn.microsoft.com/en-us/library/dtb69x08.aspx


Q: DataBindingUtil plus NavHostFragment back navigation not working I had posted a question earlier regarding NavHostFragment not working on back press. The question was not answered by anyone, hence putting a couple of days effort into it, I finally managed to figure out the issue.(I am only adding new code missing in the earlier question and changed code here, to reduce question length)
The navigation graph is changed to following:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:id="@+id/launch_navigation_graph"
            app:startDestination="@id/splashFragment">

    <fragment android:id="@+id/splashFragment" android:name="com.myapp.android.SplashFragment"
              android:label="fragment_splash" tools:layout="@layout/fragment_splash">
        <action android:id="@+id/action_splashFragment_to_fragment1"
                app:destination="@id/fragment1"
        app:popUpTo="@+id/splashFragment"
                app:popUpToInclusive="true"/>
    </fragment>
    <fragment android:id="@+id/fragment1"
              android:name="com.myapp.android.Fragment1"
              android:label="fragment1" tools:layout="@layout/fragment_register_msisdn">
        <action android:id="@+id/action_fragment1_to_fragment2"
                app:destination="@id/fragment2" app:popUpTo="@+id/fragment1"
                app:popUpToInclusive="false"/>
    </fragment>
    <fragment android:id="@+id/fragment2"
              android:name="com.myapp.android.Fragment2"
              android:label="fragment_fragment2" tools:layout="@layout/fragment_fragment2"/>
</navigation>

Some information which was missing from the previous question. The fragment binding was earlier done like this(Code below is for Fragment1, same is done in Fragment2):
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: Fragment1Binding =
        DataBindingUtil.setContentView(activity!!, R.layout.fragment1)
    binding.lifecycleOwner = this
    val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
    binding.viewModel = fragment1ViewModel
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment1, container, false)
}

The above code, with the navigation graph, now doesn't crash, but the back button simply refuse to work. It doesn't pop fragment, just exit on second back press.
Now I figured out that inflating the UI using DataBindingUtil.setContentView was the reason why my code was not working. I figured it out by creating another sample project step by step until I figured out when it stops working. I made the sample project work using data binding by using DataBindingUtil to bind to view inflated in OnCreateView like following. I remove the oncreate override.
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val rootView = inflater.inflate(R.layout.fragment1, container, false)
    val binding = DataBindingUtil.bind<Fragment1Binding>(rootView)
    binding?.lifecycleOwner = viewLifecycleOwner
    val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
    binding.viewModel = fragment1ViewModel
    return rootView
}

Now, this code works in the sample project, but when I place the same on my final project(In sample project I simply place buttons and click to navigate where as in my original project I have webservice calls and view model observing for navigating), the above code crashes with following exception when pressing back from Fragment2(similar crash in Fragment1 back press as well if I press back from Fragment1).
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/InputEventSender: Exception dispatching finished signal.
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2019-04-30 14:00:47.047 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: java.lang.IllegalArgumentException: navigation destination com.selfcare.safaricom:id/action_fragment1_to_fragment2 is unknown to this NavController
        at androidx.navigation.NavController.navigate(NavController.java:803)
        at androidx.navigation.NavController.navigate(NavController.java:744)
        at androidx.navigation.NavController.navigate(NavController.java:730)
        at androidx.navigation.NavController.navigate(NavController.java:718)
        at com.myapp.android.Fragment2.handleLaunchStatus(Fragment2.kt:53)
        at com.myapp.android.Fragment2.access$handleLaunchStatus(Fragment2.kt:18)
        at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:46)
        at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:18)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
        at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
        at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:376)
        at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
        at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:188)
        at androidx.lifecycle.LiveData.observe(LiveData.java:185)
        at com.myapp.android.Fragment2.attachLaunchObserver(Fragment2.kt:45)
        at com.myapp.android.Fragment2.onViewCreated(Fragment2.kt:37)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:895)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2092)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1822)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:298)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:288)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
        at androidx.fragment.app.FragmentActivity$1.handleOnBackPressed(FragmentActivity.java:144)
        at androidx.activity.OnBackPressedDispatcher.onBackPressed(OnBackPressedDispatcher.java:136)
        at androidx.activity.ComponentActivity.onBackPressed(ComponentActivity.java:283)
        at android.app.Activity.onKeyUp(Activity.java:3083)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2716)
        at android.app.Activity.dispatchKeyEvent(Activity.java:3366)
        at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:80)
        at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
        at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:98)
        at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2736)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:342)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5037)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4905)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4479)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4445)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4585)
        at android.view.ViewRootImpl$InputStage.apply(Vie

I googled with the exception but found nothing useful in this particular context that can solve my issue. Please help.


Q: Rest with spring-boot : Content Negotiation failed! No converter found for return value of type I am trying to get the content of a java POJO on the browser in JSON format using spring-boot 2.1.9 and spring REST. Very basic example! But I get the exception shown on the title of this post. When I annotate the POJO class with @XmlRootElement, I get the XML content on the browser. But when I try to get a list of POJOs on the browser I get the same error as with JSON. Why is the content negotiation working partially for XML and not working at all for JSON ? Thanks for every Answer.
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 03 15:17:06 CEST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:234)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)

I've already tried all the answers provided in Stackoverflow. Extending the POM file with jackson-databind, using @ResponseBody, @GetMapping instead of @RequestMapping, using produces = "application/json"...
Nothing worked for me.
package com.mayo.vina.restapi4;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Restapi4Application {

    public static void main(String[] args) {
        SpringApplication.run(Restapi4Application.class, args);
    }

}
-------------------------------------------------------------------------
package com.mayo.vina.restapi4.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mayo.vina.restapi4.domain.Limit;

@RestController
public class LimitController
{

    @RequestMapping("/limit")
    public Limit limit()
    {
        return new Limit(1, 10000);
    }
}
---------------------------------------------------------------------------
package com.mayo.vina.restapi4.domain;

//@XmlRootElement
public class Limit
{
    private int minimum;
    private int maximum;

    public Limit()
    {
    }

    public Limit(int minimum, int maximum)
    {
        this.minimum = minimum;
        this.maximum = maximum;
    }

    public int getMinimum()
    {
        return minimum;
    }

    public void setMinimum(int minimum)
    {
        this.minimum = minimum;
    }

    public int getMaximum()
    {
        return maximum;
    }

    public void setMaximum(int maximum)
    {
        this.maximum = maximum;
    }
}
--------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mayo.vina</groupId>
    <artifactId>restapi4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>restapi4</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

A: You can  try with :
@GetMapping(value = '/limit')
@ResponseBody
public Limit limit()
{
    return new Limit(1, 10000);
}

A: The following solved my problem:
So yes, just to reiterate, going into my maven repo and deleting the fasterxml folder and re-running maven is what fixed the issue for me.


Q: Latest modified row for each item I have a sql table containing multiple rows with a memberid and lastmodified date. I need to get latest modified row for each member id. This is what I have tried in EFCore 3.1.1:
var a = context.Members
    .Include(m => m.Histories.OrderByDescending(h => h.LastModifiedDate)
    .FirstOrDefault());

and it gives error: Lambda expression used inside Include is not valid
What am I missing?
UPDATE:
I tried this as well that didn't work either:
 var a = context.Histories
              .GroupBy(h => h.MemberId)
              .Select(g => g.OrderByDescending(p => p.LastModifiedDate).FirstOrDefault()).ToList();

The LINQ expression '(GroupByShaperExpression:
KeySelector: (o.MemberId),
ElementSelector:(EntityShaperExpression:
    EntityType: History
    ValueBufferExpression:
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
)
)
    .OrderByDescending(p => p.LastModifiedDate)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

A: While newer versions of EF Core do support some filtering via adding Where clauses, it's best to think of entities as a "complete" or "complete-able" representation of your data state. You either use the complete state of data, or you project to get the details you want.
For example, if you just want the last modified date for each member:
var lastModifiedDetails = context.Members
    .Select(m => new
    {
        m.MemberId,
        LastModifiedDate = m.Histories.OrderByDescending(h => h.LastModifiedDate)
            .Select(h => h.LastModifiedDate)
            .FirstOrDefault()
    }).ToList();

This would give you a collection containing the MemberId and it's LastModifiedDate.
Alternatively, if you want the complete member and a quick reference to the last modified date:
var memberDetails = context.Members
    .Select(m => new
    {
        Member = m,
        LastModifiedHistory = m.Histories.OrderByDescending(h => h.LastModifiedDate)
            .FirstOrDefault()
   }).ToList();

Here instead of trying to get the last modified date or the latest history through a Member entity, you get a set of anonymous types that project down that detail. You iterate through that collection and can get the applicable history and/or modified date for the associated Member.


Q: Moving WPF application to Android Im not sure if this is the best place for this question so please let me know if not. I have recently created a pretty simple WPF application that has a link to a SQL Database and allows information to be added, updated and deleted.
I want to port the application so I can use it on my Android phone but am unsure about the easiest way to do this. Im aware I could write a completely new application but Im wondering if there is a way I could easily use all the code ive already written or my Windows app? That way it would also make any updates/code changes easier?
Any thoughts


Q: Can't drop foreign key (using constraint name) check column/key exists I've tried to find a solution myself but haven't had any luck. I'm using MySQL version 8.0.14 and my problem is:
When trying to drop a foreign key...
alter table Employee drop foreign key fk_Employee_Contact1;

It fails...
Error Code: 1091. Can't DROP 'fk_Employee_Contact1'; check that column/key exists

I search for the constraint...
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Employee';

Which brings up (partial table)...
CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE
'fk_Employee_Contact1', 'RRAS Test Database', 'Employee', 'FOREIGN KEY'

But if I search...
SHOW CREATE TABLE Employee;

It shows it as a key...
KEY `fk_Employee_Contact1_idx` (`idContactDets`),

But not as a CONSTRAINT.
I have also tried...
alter table Employee drop foreign key fk_Employee_Contact1_idx;

Which fails with the same error code. And...
alter table Employee drop column idContactDets;

Which gives...
Error Code: 1828. Cannot drop column 'idContactDets': needed in a foreign key constraint 'fk_Employee_Contact1'

Is there any way to fix this? I'm very new to databases so please explain in simple terms if possible. Thank you. :)


Q: PHP Webhook Request I am running a WordPress site with a WooCommerce checkout. At the checkout page I am using the webhook woocommerce_thankyou as a boarding point for my code. At this Point I am selecting some data from the new my order to send the data to another website via a webhook.
I integrated the code over a custom WordPress plugin. At the moment the webhook gives me back this following error: "DigiMember - Webhook Checkout (#1): the E-Mail-Adress would not send as GET- or POST-Parameter."
What could be the problem?
<?php
    function test ($order_id) {
?>

<span>
            woocommerce_thankyou
             <?php echo $order_id;
             $order=wc_get_order($order_id);
             echo $order->get_meta('digi_first_name');
             echo $order->get_meta('digi_last_name');
             echo $order->get_meta('digi_email');

             ?>
        </span>
        <?php
//The url you wish to send the POST request to
$url = 'https://traumjob-campus.de/member?dm_webhook=1_DCqtx6Xre1oM7tuKyon5rVzAIUWvVVXofMqTRQjE9JVDgf7gLI3M198bIeD5';

//The data you want to send via POST
$fields = [
    'digi_first_name'      => 'user',
    'digi_last_name' => 'test',
    'digi_email'         => 'test@user.de'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
echo $result;
?>


Q: Search specific words in pdf and return only pdf link where words were found (Python) I am trying to search for multiple words in many PDFs. Links to these PDFs are saved in a dataframe. The goal is for python to return a text stating "The words are located in pdf link"). Here is the code I have so far: (FYI g7 is the name of the dataframe where the links are saved).The issue here is that the code returns the same link multiple times for every time the word is found.
The dataframe (named g7) looks like this:
    URL
0   https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Senegal-RMNCAH-Activity_English-Version.pdf
1   https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Activit%C3%A9-RMNCAH-S%C3%A9n%C3%A9gal_Version-Fran%C3%A7aise.pdf
2   https://westafricatradehub.com/wp-content/uploads/2021/08/Senegal-Health-RFA-Webinar-QA.pdf
3   https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Catalytic-Business-Concepts-Round-2.pdf
4   https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Concepts-d%E2%80%99Affaires-Catalytiques-2ieme-Tour.pdf
5   https://westafricatradehub.com/wp-content/uploads/2021/06/APS-WATIH-1247_Research-Development-Round-2.pdf

The code is as follows:
import glob
import pathlib
import PyPDF2
import re
import os
for i in range(g7.shape[0]):
    pdf_link=g7.iloc[i,0]
    download_file(pdf_link, f"pdf_{i}")
    text = textract.process(f"/Users/fze/pdf_{i}.PDF")
    # open the pdf file
    object = PyPDF2.PdfFileReader(f"/Users/fze/pdf_{i}.PDF")
    all_files = glob.glob('/Users/fze/*.pdf') #User input: give path to your downloads folder file path
    latest_pdf_path = max(all_files, key=os.path.getctime)

    path = pathlib.PurePath(latest_pdf_path)
    latest_pdf_name=path.name
    print(latest_pdf_name)

    # get number of pages
    NumPages = object.getNumPages()
    # define keyterms
    search_word = 'organization'
    # extract text and do the search
    for i in range(0, NumPages):
            page = object.getPage(i)
            text = page.extractText()
            search_text = text.lower().split()
            for word in search_text:
                if search_word in word:
                    print("The word '{}' was found in '{}'".format(search_word,pdf_link))

Thank you !


Q: Change a View with a procedure This is the source of a view , i use this view as the base of a procedure named buscacancelados:
 SELECT     NUMERO  FROM dbo.CTRC
 WHERE     (EMITENTE = 504) AND (MONTH(EMISSAODATA) = 3)
 AND (YEAR(EMISSAODATA) = 2013)

This procedure returns the missing numbers in a set
alter   proc buscarcancelado  (@emp int) as
 begin
 set nocount on;
 declare @min int   --- declare the  variavels to be used
 declare @max int
 declare @I int

 IF OBJECT_ID ('TEMP..#TempTable') is not null --  Controls if  exists this table
 begin
        drop table #TempTable -- If exist delete
 end

 create table #TempTable
              (TempOrderNumber int)-- create a temporary table

 SELECT @min = ( SELECT MIN (numero)
                 from controlanum  with (nolock))  -- search the min value of the set

 SELECT @max =  ( SELECT Max (numero)
                  from controlanum  with (nolock)) -- search the max value of the set

 select @I = @min  -- control where begins the while

 while @I <= @max --  finish with the high number
       begin
             insert into #TempTable
             select @I
             select @I = @I + 1
       end
 select tempordernumber from #TempTable
 left join controlanum O with (nolock)
 on TempOrderNumber = o.numero where o.numero is null
 end

I want to change the view controlanum with this procedure
        create proc filtraperiodo (@emp int,@mes int,@ano int)as
        select numero from ctrc where
        EMITENTE = 504
        and MONTH (EMISSAODATA ) = 3 and YEAR (EMISSAODATA)=2013

I want something like this
          SELECT @min = ( SELECT MIN (numero) from  filtraperiodo 504,2,2013

A: Create controlanum as a table-valued function instead of a view
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID('[dbo].[controlanum]') AND XTYPE IN ('FN', 'IF', 'TF'))
        DROP FUNCTION [dbo].[controlanum]
    GO

    CREATE FUNCTION [dbo].[controlanum] (
        @emp int
       ,@mes int
       ,@ano int
    )

    RETURNS @numeros TABLE (numero int)

    AS
    BEGIN

      INSERT @numeros
      SELECT numero
        FROM ctrc WITH (NOLOCK)
       WHERE EMITENTE               = @emp
         AND MONTH (EMISSAODATA )   = @mes
         AND YEAR (EMISSAODATA)     = @ano

      RETURN

    END
    GO

Everywhere you reference controlanum, pass it your 3 filter values.  For instance:
    --...other code here...

    SELECT @min = MIN(numero)
      FROM dbo.controlanum(@emp, @mes, @ano)

    SELECT @max = MAX(numero)
      FROM dbo.controlanum(@emp, @mes, @ano)

    --...other code here...

    SELECT tempordernumber
      FROM #TempTable A
      LEFT JOIN dbo.controlanum(@emp, @mes, @ano) O
        ON A.TempOrderNumber <> O.numero
     WHERE O.numero IS NULL


Q: Python method to get integers from a string with limitation (in some range) Is there a module in python to get integers from string in given range (with limit/restriction) ?
It can be useful to make code cleaner.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | bool: # (or False directly)
    try:
        number = int("".join(filter(str.isdigit, string)))
        if low_boundary < number < high_boundary:
            return number
        else:
            return False
    except ValueError:  # Empty message or out of limit
        return False

Usage:
...
if not amount := get_int_from_str(string=input(), low_boundary = 10, high_boundary = 20)
    ...
...

A: Don't fight exceptions. If you can't parse a string as an integer, let the ValueError be raised. If the number is out of range, raise a different ValueError. Otherwise, return a value that is guaranteed to be in the requested range.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int:
    x = int(str)  # May raise
    if x < low_boundary or x > high_boundary:
        raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}")
    return x

The caller knows better than your function what to do if the string cannot produce an in-range integer, and raising an exception forces them to consider the worst-case scenario, rather than letting them assume the function worked and encountering an error later.

As a conventional alternative, you can return None to indicate the lack of a suitable int value. Unlike False, None cannot be confused with 0, but it can still be ignored altogether to cause problems later. (And None by itself doesn't tell you if the string wasn't parseable or if the parsed number was simply out of range.)
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
    try:
        x = int(str)
    except ValueError:
        return None

    if x < low_boundary or x > high_boundary:
        return None

    return x

or, to avoid repeating the return None statement:
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
    try:
        x = int(str)
        if x < low_boundary or x > high_boundary:
            raise ValueError
    except ValueError:
        return None

    return x

A: def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False:
    number = "".join(filter(str.isdigit, string))
    if number:
        number = int(number)
        if low_boundary < number < high_boundary:
            return number
    return False

Note: Using not operator with the output of the function does not distinguish between False and 0 as not False and not 0 will evaluate to True. Here you can differentiate by checking the output with amount is not False condition.


Q: How do I make links that were in the menu be on the nav bar on bigger screens? There are links that were shown on the side of the page as a menu when a button that was in the header was clicked. I want the button to be hidden and for those links to show up in the header instead. But if hide the button, the links do not show up, regardless of if I make the display: block or not. The only thing that happens is that the button is gone, but so are the links.
I have JavaScript code that hides and shows the links when the button is clicked
How do I change the position of the links?

header {
  height: 3.4rem;
  display: grid;
  align-items: center;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right i {
  margin-right: 1rem;
}

.menu {
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 1;
  background-color: #000;
  /* margin-left: 4rem; */
  margin-top: 0;
}

@media screen and (min-width: 992px) {
  .right i {
    display: none;
  }
  .menu {
    display: block;
  }
  .top-menu {
    display: flex;
    top: 0;
  }
  .header-container {
    display: flex;
  }
}

      Premium
      Support
      Download

      Account
      Log out

A: You want links on Nav Bar to show when the site is viewed via PC or Laptop screen. And you want the links to collapse in button when site is viewed via mobile.
When viewed on PC Screen:

I did it with Bootstrap, you can also use jQuery for simplicity.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggler1" aria-controls="navbarToggler1" aria-expanded="false" aria-label="Toggle navigation">

      </button>

              Features

              Blog

              About

              Contact

Using simple jQuery

#show{
  display:none;
}
#content{
  display:none;
}
@media only screen and (max-width: 600px)
{
  div{
    display:none;
  }
  #show{
    display:inline;
  }
}
<button id="show">Show</button>

      pricing

      features

      pricing

      features

Live Result with Code


Q: How to stop thinking "relationally" At work, we recently started a project using CouchDB (a document-oriented database).  I've been having a hard time un-learning all of my relational db knowledge.
I was wondering how some of you overcame this obstacle?  How did you stop thinking relationally and start think documentally (I apologise for making up that word).
Any suggestions?  Helpful hints?
Edit: If it makes any difference, we're using Ruby & CouchPotato to connect to the database.
Edit 2: SO was hassling me to accept an answer.  I chose the one that helped me learn the most, I think.  However, there's no real "correct" answer, I suppose.

A: It's all about the data. If you have data which makes most sense relationally, a document store may not be useful. A typical document based system is a search server, you have a huge data set and want to find a specific item/document, the document is static, or versioned.
In an archive type situation, the documents might literally be documents, that don't change and have very flexible structures. It doesn't make sense to store their meta data in a relational databases, since they are all very different so very few documents may share those tags. Document based systems don't store null values.
Non-relational/document-like data makes sense when denormalized. It doesn't change much or you don't care as much about consistency.
If your use case fits a relational model well then it's probably not worth squeezing it into a document model.
Here's a good article about non relational databases.
Another way of thinking about it is, a document is a row. Everything about a document is in that row and it is specific to that document. Rows are easy to split on, so scaling is easier.

A: In CouchDB, like Lotus Notes, you really shouldn't think about a Document as being analogous to a row.
Instead, a Document is a relation (table).
Each document has a number of rows--the field values:
ValueID(PK)  Document ID(FK)   Field Name        Field Value
========================================================
92834756293  MyDocument        First Name        Richard
92834756294  MyDocument        States Lived In   TX
92834756295  MyDocument        States Lived In   KY

Each View is a cross-tab query that selects across a massive UNION ALL's of every Document.
So, it's still relational, but not in the most intuitive sense, and not in the sense that matters most: good data management practices.

A: Document-oriented databases do not reject the concept of relations, they just sometimes let applications dereference the links (CouchDB) or even have direct support for relations between documents (MongoDB). What's more important is that DODBs are schema-less. In table-based storages this property can be achieved with significant overhead (see answer by richardtallent), but here it's done more efficiently. What we really should learn when switching from a RDBMS to a DODB is to forget about tables and to start thinking about data. That's what sheepsimulator calls the "bottom-up" approach. It's an ever-evolving schema, not a predefined Procrustean bed. Of course this does not mean that schemata should be completely abandoned in any form. Your application must interpret the data, somehow constrain its form -- this can be done by organizing documents into collections, by making models with validation methods -- but this is now the application's job.

A: may be you should read this
http://books.couchdb.org/relax/getting-started
i myself just heard it and it is interesting but have no idea how to implemented that in the real world application ;)

A: I think, after perusing about on a couple of pages on this subject, it all depends upon the types of data you are dealing with.
RDBMSes represent a top-down approach, where you, the database designer, assert the structure of all data that will exist in the database.  You define that a Person has a First,Last,Middle Name and a Home Address, etc.  You can enforce this using a RDBMS.  If you don't have a column for a Person's HomePlanet, tough luck wanna-be-Person that has a different HomePlanet than Earth; you'll have to add a column in at a later date or the data can't be stored in the RDBMS.  Most programmers make assumptions like this in their apps anyway, so this isn't a dumb thing to assume and enforce.  Defining things can be good.  But if you need to log additional attributes in the future, you'll have to add them in.  The relation model assumes that your data attributes won't change much.
"Cloud" type databases using something like MapReduce, in your case CouchDB, do not make the above assumption, and instead look at data from the bottom-up.  Data is input in documents, which could have any number of varying attributes.   It assumes that your data, by its very definition, is diverse in the types of attributes it could have.  It says, "I just know that I have this document in database Person that has a HomePlanet attribute of "Eternium" and a FirstName of "Lord Nibbler" but no LastName."  This model fits webpages:  all webpages are a document, but the actual contents/tags/keys of the document vary soo widely that you can't fit them into the rigid structure that the DBMS pontificates from upon high.  This is why Google thinks the MapReduce model roxors soxors, because Google's data set is so diverse it needs to build in for ambiguity from the get-go, and due to the massive data sets be able to utilize parallel processing (which MapReduce makes trivial).  The document-database model assumes that your data's attributes may/will change a lot or be very diverse with "gaps" and lots of sparsely populated columns that one might find if the data was stored in a relational database.  While you could use an RDBMS to store data like this, it would get ugly really fast.
To answer your question then:  you can't think "relationally" at all when looking at a database that uses the MapReduce paradigm.  Because, it doesn't actually have an enforced relation.  It's a conceptual hump you'll just have to get over.

A good article I ran into that compares and contrasts the two databases pretty well is MapReduce: A Major Step Back, which argues that MapReduce paradigm databases are a technological step backwards, and are inferior to RDBMSes.  I have to disagree with the thesis of the author and would submit that the database designer would simply have to select the right one for his/her situation.

A: One thing you can try is getting a copy of firefox and firebug, and playing with the map and reduce functions in javascript. they're actually quite cool and fun, and appear to be the basis of how to get things done in CouchDB
here's Joel's little article on the subject : http://www.joelonsoftware.com/items/2006/08/01.html


Q: Why would you use Ramda's lenses over evolve/path? Is there some functionality that lenses offer that you cannot get with path/assocPath/evolve/adjust?


Q: Cocos2D: Multiple actions: CCMoveTo CCAnimate I don´t understand, I absolutely cannot get this to work, I want a sequence of actions that plays an animation and moves the sprite using the CCAnimate ans CCMoveTo classes. Is there a bug or something special about these classes, cause it will not move nor animate when stringing it together in a CCSequence of actions like this.
    action = [CCSequence actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCAnimate actionWithAnimation:self.walkingAnim],
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)], nil];
 [self runAction:action];

I

A: If you want the move and animate action to run paralel you can use:
Option1:  use CCSpawn instead of a CCSequence. CCSequence is needed because you would like to call a function after completion.
id action = [CCSpawn actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCAnimate actionWithAnimation:self.walkingAnim],
                               nil];

id seq = [CCSequence actions:
                              action,
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
                               nil];

[self runAction:seq];

Option2: just add any action multiple times and will be run in paralel. Because of the func-call a CCSequence again needed:
id action = [CCSequence actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
                               nil];
[self runAction:action];
[self runAction:[CCAnimate actionWithAnimation:self.walkingAnim]];

A: What this sequence does is:

*

*move self to the destination

*once arrived at destination, play the walking animation

*when the walk animation is finished, run the selector

I bet you meant to run the move and animate actions separately and at the same time (each with their own call to runAction) and not within a sequence.


Q: Could not display data from php mysql in listview java Please help im new in java...
im not able to display data in listview
PHP side
    <?
    $objConnect = mysql_connect("my server","username here"," my password");
    $objDB = mysql_select_db("db");

    $strSQL = "SELECT * FROM image WHERE 1  ";
    $objQuery = mysql_query($strSQL);
    $intNumField = mysql_num_fields($objQuery);
    $resultArray = array();
    while($obResult = mysql_fetch_array($objQuery))
    {
        $arrCol = array();
        for($i=0;$i<$intNumField;$i++)
        {
            $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
        }
        array_push($resultArray,$arrCol);
    }

    mysql_close($objConnect);

    echo json_encode($resultArray);
?>

I have 3 layout
main layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F3E70D" >

   <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:padding="10dip" >

       <TextView
           android:id="@+id/tvordername"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textColor="#000000"
           android:textStyle="bold"
           android:text="TextView" />

       <TextView
           android:id="@+id/textView2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="TextView" />

       <ListView
           android:id="@+id/listView1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" >
       </ListView>

   </LinearLayout>

</ScrollView>

Second layout
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <ImageView
            android:id="@+id/ColImgPath"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/ColImgID"
            android:text="Column 1" />
        <TextView
            android:id="@+id/ColImgDesc"
            android:text="Column 2" />
    </TableRow>
</TableLayout>

Third layout is use to display more detail and single record
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/fullimage"
        android:layout_width="match_parent"
        android:layout_height="245dp"/>
    <TextView
        android:id="@+id/custom_full_order"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        >

    </TextView>
</LinearLayout>

Java side my complete code
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.android.library.DatabaseHandler;
import com.example.android.library.UserFunctions;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class OrderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);

        //listview
        final ListView lstview1 = (ListView)findViewById(R.id.listView1);

        String url = "my server address http:";

        try{
            JSONArray data = new JSONArray(getJSONUrl(url));

            final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String>map;

            for(int i= 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("ImageID", c.getString("ImageID"));
                map.put("ImageDesc", c.getString("ImageDesc"));
                map.put("ImagePath", c.getString("ImagePath"));
                MyArrList.add(map);
            }

            lstview1.setAdapter(new ImageAdapter(this,MyArrList));

            final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
            final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

            lstview1.setOnItemClickListener(new OnItemClickListener(){

                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    View layout = inflater.inflate(R.layout.custom_fullorder_dialog, (ViewGroup) findViewById(R.id.fullimage));
                    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
                try
                {
                    image.setImageBitmap(loadBitmap(MyArrList.get(position).get("Imagepath")));
                } catch (Exception e){
                    //if get error
                    image.setImageResource(android.R.drawable.ic_menu_report_image);
                }
                imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                imageDialog.setTitle("View : " + MyArrList.get(position).get("comment"));
                imageDialog.setView(layout);
                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });
                    imageDialog.create();
                    imageDialog.show();
                }

            });
        } catch(JSONException e){
            e.printStackTrace();
        }

    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list){

            context = c;
            MyArr = list;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return MyArr.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(convertView == null){
                convertView = inflater.inflate(R.layout.activity_column, null);
            }
            //colimage
            ImageView imageView =(ImageView) convertView.findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height= 100;
            imageView.getLayoutParams().width= 100;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try
            {
                imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));

            } catch (Exception e){
                //if get error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            //colposition
            TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
            txtPosition.setPadding(10, 0, 0, 0);
            txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));

            //colpicname
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("DEesc : " + MyArr.get(position).get("ImageDesc"));

            return convertView;
        }

    }
    //get json code from url
    public String getJSONUrl(String url){
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try{
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while((line = reader.readLine()) != null){
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file...");
            }
        } catch (ClientProtocolException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    //get image resource from url
    private static final String TAG = "ERROR";
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static Bitmap loadBitmap(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in,out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSamplesize=1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        } catch (IOException e){
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }
        return bitmap;
    }

    private static void closeStream(Closeable stream){
        if(stream != null) {
            try{
                stream.close();
            } catch (IOException e){
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1){
            out.write(b, 0, read);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.order, menu);
        return true;
    }

}

my logcat
01-26 21:58:35.594: W/System.err(14298): org.json.JSONException: Value <? of type java.lang.String cannot be converted to JSONArray
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSON.typeMismatch(JSON.java:111)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:96)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:108)
01-26 21:58:35.594: W/System.err(14298):    at com.example.androidjhfong.OrderActivity.onCreate(OrderActivity.java:77)
01-26 21:58:35.594: W/System.err(14298):    at android.app.Activity.performCreate(Activity.java:5231)
01-26 21:58:35.599: W/System.err(14298):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Looper.loop(Looper.java:136)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.main(ActivityThread.java:5139)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invokeNative(Native Method)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invoke(Method.java:515)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
01-26 21:58:35.599: W/System.err(14298):    at dalvik.system.NativeStart.main(Native Method)
01-26 21:58:35.719: I/Timeline(14298): Timeline: Activity_idle id: android.os.BinderProxy@423fd758 time:785573323

A: You have real mess in your code. Firstly you shouldn't connect to web in main thread (it blocks app, cause "application not responding"). For fetching JSON I would recommend RoboSpice.
Secondly in ImageAdapter.getItem you should return MyArr.get(position) not position.

A: I think greenapps and MAGx2 have the right hints for the solution.
I'd like to add that it might be better to use a few open source libraries for the other things.

*

*picasso for image downloading + displaying

*gson for json parsing

*okhttp for normal downloads

Also, don't use things like this:
imageView.getLayoutParams().height= 100;

It really messes up when you view on other devices with different DPI


Q: Image(Absolute Positioned) Horizontally center in a Relative Positioned container I want to center an absolute positioned image  horizontally in a relative positioned container. I tried to do with css. But I could't and i did in Jquery
http://jsfiddle.net/CY6TP/ [This is i tried to do in Jquery]
**Guys can anyone help me to do this in CSS.**
Thanks in advance

A: try this:
var width=$('.main').width();
var height=$('.main').height();

$('a').css(
{
"position":"absolute",
"bottom":"50%",
"margin-top":(height/2),
"left":(width/2)-50

});

DEMO
UPDATE
In CSS
.main a{
   bottom:50%;
    margin-top:-150px;
    position:absolute;
    left:75px;
}

DEMO

A: You can set all in css like this :
a{
position : absolute ;
height : 10px;
width : 100px;
top : 50%;
margin-top : -5px;
left : 50%;
margin-left : -50px;}

Demo

A: try this to make it horizontally center
a{
    position: absolute;
    text-align: center;
    width: 100%;
}

OR this to make it horizontally and vertically both center
a {
    height: 100%;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

A: .main img { top:50%; left:50%; margin: -11px 0 0 -50px; position: absolute;}

Is this you want?

A: If your height is fixed, you could use something like this maybe?
CSS:
#div1 {
    width:100%;
    height:100px;
    text-align:center;
}

#div1 img {
    line-height:100px;
}

HTML:


Q: geom_bar: stack without adding I want a bar chart that looks stacked, but that the values are the actual values rather than being additive.  I'm graphing things at ages, and ages don't "add".
The data below show that the oldest animal lives to be 31 days old.  However, the graph indicates a value in the 60s because it is adding the days together.
x <- data.frame(species = c("Alpha", "Alpha", "Alpha","Beta", "Beta", "Beta","Gamma", "Gamma", "Gamma"), lifestage = factor(c("infant", "juvenile", "adult", "infant", "juvenile", "adult", "infant", "juvenile", "adult"),levels = c("infant", "juvenile", "adult")), age = c(10, 20, 30, 11, 21, 31, 9, 19, 29))

ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
       geom_bar(stat = "identity", position = position_stack(reverse = TRUE)) +
       coord_flip()

How can I show the actual ages at which these events happen?

A: Figured it out - it's not a stacked graph I want, but a dodged graph with full overlap / no offset.  position_dodge to the rescue!
ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) +
          geom_bar(stat="identity", position = position_dodge(width = 0), width = 2)   +
          coord_flip()


Q: Change NavigationPage Backbutton color from DynamicResource Found this for change to change the color of the backbutton .
NavigationPage.SetIconColor(this, Color.FromHex("#FFFF00"));

The backgroudcolor of the page i change with DynamicResource.
Invul.xaml.cs
  App.Current.Resources["defaultBackgroundColor"] = Preferences.Get("BackgroundColor", "#1D252D");

For the Backcolor of the backbutton i tryed this but not working because Color.FromHex i think ,can i change the FromHex part in to ?
  NavigationPage.SetIconColor(this, Color.FromHex("{DynamicResource defaultBackgroundColor}"));

A: If you want to use color from ResourceDictionary , you can access it first and pass the result color to the second parameter of method NavigationPage.SetIconColor.
Please refer to the following code:
        Color color = (Color)Application.Current.Resources["defaultBackgroundColor"];
        NavigationPage.SetIconColor(this, color);

The defaultBackgroundColor is a color in Application.Resources:
   <Application.Resources>
    <ResourceDictionary>
        <!-- Colors -->
        <Color x:Key="defaultBackgroundColor">Red</Color>
        <Color x:Key="Yellow">#ffd966</Color>
    </ResourceDictionary>
</Application.Resources>


Q: Join related Issue New to SQL
Suppose we have two tables
One has got the ID and Name column :
+----+-------+
| ID |  Name |
+----+-------+
|  1 | Sam   |
|  1 | Dan   |
+----+-------+

and the second one has also got two columns as follow :
+----+------------+
| ID |  Relatives |
+----+------------+
|  1 | Uncle      |
|  2 | Aunty      |
+----+------------+

If we do inner join we would only get the rows where the condition satisfies. But i want the output to be Like
+------+------------+
|  ID  |  Relatives |
+------+------------+
| 1    | Uncle      |
| NULL | Aunty      |
+------+------------+

once only the value in the ID column should be shown. If the occurrence is twice or thrice it should come as null.
Just tell me if it is possible or not? and How for both the cases.

A: Try this:
SELECT
  T1.Id,
  T2.Relatives
FROM SecondTable T2
LEFT JOIN FirstTable T1
  ON T1.ID = T2.ID
GROUP BY T1.Id,
         T2.Relatives

This is what I get exactly:
CREATE TABLE #a (
  id int,
  name varchar(10)
)
CREATE TABLE #b (
  id int,
  name varchar(10)
)
INSERT INTO #a
  VALUES (1, 'sam')
INSERT INTO #a
  VALUES (1, 'Dan')
INSERT INTO #b
  VALUES (1, 'Uncle')
INSERT INTO #b
  VALUES (2, 'Aunty')

SELECT
  T1.Id,
  T2.name
FROM #b T2
LEFT JOIN #a T1
  ON T1.ID = T2.ID
GROUP BY T1.Id,
         T2.name

DROP TABLE #a
DROP TABLE #b

Output:
Id      name
NULL    Aunty
1       Uncle

Hope, this is what you ask in your question.

A: As your question is not clear, so assuming that you need to retrieve id from table a and name from table b and you also want to avoid duplicate rows, then an option could be to use distinct along with left join:
select distinct a.id, b.name
from b
left outer join a
on b.id = a.id
order by id desc

Result:
+------+-------+
|  id  | name  |
+------+-------+
| 1    | Uncle |
| NULL | Aunty |
+------+-------+

DEMO


Q: Creating data.frame of multiple random samples from a vector in R? I have the vector X and I would like to generate a data.frame of 6 integer samples of size 4. In other words, I would like to have a data.frame of 6 * 4 dimension. I tried the following the following but its throwing out lenght argument error.
set.seed(123)

X <- c(4,10,15,100,50,31,311,225,85,91)

S <- replicate(X, sample.int(n = 6, size = 4))

A: We may need
replicate(4, sample(X, size = 6))

Or
replicate(6, sample(X, size = 4))

A: Another base R solution.
set.seed(123)

X <- c(4,10,15,100,50,31,311,225,85,91)

dat <- as.data.frame(lapply(1:4, function(i) sample(X, size = 6))) %>%
  setNames(paste0("V", 1:4))

dat
#    V1  V2  V3  V4
# 1  15  50  50  85
# 2  91 100  15  15
# 3  10  31  85 225
# 4 225 225   4  10
# 5  31   4 100 311
# 6  85  10 311   4


Q: How to configure EC2 security group to permit loopback via public IP address? I have to run a program on an EC2 that reads the host's public IP address from config (which I don't appear to be able to easily change), and then connects to it, i.e. it's looping back to the instance via the public IP address.
I can't find out how to create a security group that can loopback to the the EC2 instance. My rules are:
outbound: 0.0.0.0/0 all tcp
inbound: [private IP/32, 127.0.0.1/32, public IP/32] all tcp 4440 (the port I need)
None of the inbound IPs work. I'm testing this by telnetting on the host to the public IP: telnet x.x.x.x 4440, and I'm never able to (where x.x.x.x is my public IP). I can do it by specifying 127.0.0.1 though, so the server I'm connecting to is online and bound correctly. I can also access the server through my browser. I just can't loopback. The connection hangs, which is why I think it's a security group issue.
How can I allow this program - which tries to connect to the public IP from the instance - to connect to the same instance by its public IP address?

A: I just did a test (using ICMP rule) , you have to add a rule in the security group as you said. you should add it normally, and set the source to 1.2.3.4/32 (following your example). please note that I am using Elastic IP in my tests.

A: According to the docs, it should also be possible to list that security group as its own source.  This would permit the loopback even if the IP address changes due to a stop/start.

Another security group. This allows instances associated with the specified security group to access instances associated with this security group. This does not add rules from the source security group to this security group. You can specify one of the following security groups:

*

*The current security group

*A different security group for the same VPC

*A different security group for a peer VPC in a VPC peering connection


Q: Airflow 2.0.2 - SnowflakeHook can't read query located in directory we're moving to airflow 2.0 and I noticed the below error, it seems SnowflakeHook can't read the query located in our 'sql' directory, this was running fine in airflow 1.x:

snowflake.connector.errors.ProgrammingError: 001003 (42000):
019c5ac7-0602-31b5-0000-01b526e4fa46: SQL compilation error: syntax
error line 1 at position 0 unexpected 'sql'.
During handling of the above exception, another exception occurred:
common.snowflake.exceptions.SQLCompilationSnowflakeException:  001003
(42000): 019c5ac7-0602-31b5-0000-01b526e4fa46: SQL compilation error:
syntax error line 1 at position 0 unexpected 'sql'. Error occured
while processing query(019c5ac7-0602-31b5-0000-01b526e4fa46):
sql/my_query.sql

Below is the class we've created:
class SnowQueryOperator(BaseOperator):
    template_fields = ['sql']

    @apply_defaults
    def __init__(self,
                 sql,
                 params=None,
                 warehouse=Variable.get('default_snowflake_warehouse'),
                 *args,
                 **kwargs):
        super().__init__(*args, **kwargs)
        self.sql = sql
        self.params = params
        self.warehouse = warehouse

    def execute(self, context):
        sf_hook = SnowflakeHook(warehouse=self.warehouse)
        sf_hook.execute_query(self.sql)

and this is how we use it:
t4 = SnowQueryOperator(
    task_id='running_snowflake_query',
    sql='sql/my_query.sql',
    retries=0,
    pool='airflow')

A: I don't think this code worked on Airflow 1.10
you are missing template_ext that will allow you to read from .sql files.
class SnowQueryOperator(BaseOperator):
    template_fields = ('sql')
    template_ext = ('.sql',)

I'm not clear on why you implemented this operator on your own. Airflow has Snowflake provider which has SnowflakeOperator.
You can install it with pip install apache-airflow-providers-snowflake and then import the operator as from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator


Q: Anyone know whats wrong with my code. Its not displaying anything in the console Getting the average grade and displaying the letter grade accordingly
const grade = [70, 90, 50] / 3;

switch (grade) {
    case grade < 60:
        console.log("F");
        break;

    case grade >= 60 && grade < 70:
        console.log("D");
        break;

    case grade >= 70 && grade < 80:
        console.log("C");
        break;

    case grade >= 80 && grade < 90:
        console.log("B");
        break;

    case grade >= 100:
        console.log("Congrats on your A!");
}

Thanks to anyone who can help!

A: This line const grade = [70, 90, 50] / 3; returns NaN So other condition with switch case will not work as you expected. I think you want to achieve this after calculating the average of the 3 subjects. You can find the sum of 3 subjects using Array.prototype.reduce() and Then use switch...case syntax properly. See more about switch-case
So try like this way,

const grade = [70, 90, 50].reduce((a, b) => a + b, 0) / 3;

switch (true) { // see this line
  case grade < 60:
    console.log("F");
    break;
  case grade >= 60 && grade < 70:
    console.log("D");
    break;
  case grade >= 70 && grade < 80:
    console.log("C");
    break;
  case grade >= 80 && grade < 90:
    console.log("B");
    break;
  case grade >= 100:
    console.log("Congrats on your A!");
}

OR Less typing with if..else if version without using break; though.

const grade = [70, 90, 50].reduce((a, b) => a + b, 0) / 3;

if(grade < 60)
    console.log("F");
else if (grade >= 60 && grade < 70)
    console.log("D");
else if (grade >= 70 && grade < 80)
    console.log("C");
else if (grade >= 80 && grade < 90)
    console.log("B");
else if (grade >= 100)
    console.log("Congrats on your A!");

A: To get the average, you need to first add all the values in the array together before dividing them by the amount of grades there is:
const average = grades.reduce((acc, val) => acc + val, 0) / grades.length;

After that, you should use if/else-if blocks instead of switch to compare the values.

const grades = [70, 90, 50]
const average = grades.reduce((acc, val) => acc + val, 0) / grades.length;

console.log(average)

if (average < 60) console.log("F");
else if (average < 70) console.log("D");
else if (average < 80) console.log("C");
else if (average < 90) console.log("B");
else console.log("Congrats on your A!");

You don't need to check for the prior condition not applying (average >= 60 && and so on), since this uses else id, this also means that you don't need to specify a condition for the A grade, since all other conditions don't aplly.

A: If you put expressions in the case labels, then the switch value needs to be true or false (usually true).
That said, while you can put expressions in the case labels (in JavaScript, unlike many other languages), if...else if...else is more common.
Additionally, this line:
const grade = [70, 90, 50] / 3;

...sets grade to NaN, because the / coerces the array to a number, which goes by way of converting it to a string first ("70,90,50") and then "70,90,50" can't be implicitly converted to a number, so the result is NaN. NaN / 3 is NaN because any math operation with NaN results in NaN.
Finally, the last grade >= 100 condition looks dodgy. It means you aren't handling 90...99. You probably just want default (or else) there.
I assume you wanted to get the average grade instead, which you can do with reduce (or a simple loop):
const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;

So doing that and using switch (true):

const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
switch (true) {
    case grade < 60:
        console.log("F");
        break;

    case grade >= 60 && grade < 70:
        console.log("D");
        break;

    case grade >= 70 && grade < 80:
        console.log("C");
        break;

    case grade >= 80 && grade < 90:
        console.log("B");
        break;

    default:
        console.log("Congrats on your A!");
}

You don't need those grade >= 60 && and such, since each case label is tested in source code order and the first one wins.

const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
switch (true) {
    case grade < 60:
        console.log("F");
        break;

    case grade < 70:
        console.log("D");
        break;

    case grade < 80:
        console.log("C");
        break;

    case grade < 90:
        console.log("B");
        break;

    default: // Made this default instead
        console.log("Congrats on your A!");
}

Or the if...else if...else version:

const grade = [70, 90, 50].reduce((a, b) => a + b) / 3;
if (grade < 60) {
    console.log("F");
} else if (grade < 70) { //
    console.log("D");
} else if (grade < 80) {
    console.log("C");
} else if (grade < 90) {
    console.log("B");
} else {
    console.log("Congrats on your A!");
}


Q: mongodb-schema MongoDB Schema is used to validate if the incoming data is valid or not.


Q: Prettify JSON object alert I have a JSON object and when i alert it i get this:

and i want to get this:

function getNameById(id){
    return usersArray.find(item => item.id === id).name;
}

var usersArray = [
          {"id":"135","name":"Jenny"},
                    {"id":"162","name":"Kelly"}
                 ];
$("#submit").click(function (e) {
    var errors = {};

    $(".validation").each(function(){
       var worker_id = $(this).attr('id').replace(/[^\d]/g, '');
       var w_name = getNameById(worker_id);
       if(!errors[w_name]) errors[w_name] = [];
       if ( $(this).val() == "" ) {
           errors[w_name].push( $(this).attr('id').replace(/[^a-zA-Z]/g, '') + " must be filled!");
           //errors[w_name].push("second number must be smaller than first");
       }
       if ( $(this).attr('id') == "second-"+worker_id  && ($(this).val() > $('#first-'+worker_id+'').val())) {
         errors[w_name].push("second number must be smaller than first");
       }
    });

    alert(JSON.stringify(errors, null, 2));
    e.preventDefault();
    e.stopPropagation();

});

<form method="post">
  First<input id="first-135" class="validation" name="first" type="text" value="5">

  Second<input id="second-135" class="validation" name="second" type="text" value="8">

  Signature<input id="signature-135" class="validation" name="signature" type="text">

<input id="submit" type="submit" value="Submit">
</form>

How can i achieve that?

A: Transform your object to a string like this

let obj = {
  "Jenny" : [
    "Second number must be smaller than first",
    "Signature must be filled !"
  ]
};

let str = "";
Object.keys(obj).forEach(k => {
  str += k + ":\n";
  str += obj[k].join(",\n");
});

console.log(str);

A: Extract the data from the JSON data that you have in errors instead of running JSON.stringify directly. You should be able to get the data like this: errors["Jenny"] to get a list of the errors. Then combine them into a string according to your liking.

A: I honestly don't think your question has absolutely anything to do with JSON. The only reason why some JSON even shows up is because you're generating it for the alert():
alert(JSON.stringify(errors, null, 2));
   // ^^^^^^^^^^^^^^ This generates JSON

If you want to concatenate some array items you can use a combination of the concatenation operator (+) and Array.join():
alert(w_name + ":\n" + errors[w_name].join(",\n"));

Tweak format to your liking.

var w_name = "Jenny";
var errors = {};

errors[w_name] = [];
errors[w_name].push("Second number must be smaller than first");
errors[w_name].push("Signature must be filled!");

alert(w_name + ":\n" + errors[w_name].join(",\n"));