text:
Q: "Column 'id' in where clause is ambiguous" after inner joining? I had this select query which worked fine until I performed an inner join.
$id = (int) $_GET['id'];
$data = mysql_query("
SELECT
    events.start_datetime,
    events.EVENT_NAME,
    events.START_TIME,
    events.END_TIME,
    events.VENUE_LOCATION,
    venues.VENUE_NAME
FROM
    events
INNER JOIN venues
        ON events.VENUE_LOCATION = venues.ID
WHERE
    id = ".$id) or die(mysql_error());

The $id variable is so that the query loads data from a row depending on the url (ie: page.php?id=1).
Any idea what's wrong? Thanks

A: In the WHERE clause, change id to events.id or venues.id, whichever you mean. Unfortunately, neither MySQL or I can guess which one you mean.

A: venues probably has an id field too, so you need to specify events.id, not just id, i.e.
$id = (int) $_GET['id'];
$data = mysql_query("
SELECT
    events.start_datetime,
    events.EVENT_NAME,
    events.START_TIME,
    events.END_TIME,
    events.VENUE_LOCATION,
    venues.VENUE_NAME
FROM
    events
INNER JOIN venues
        ON events.VENUE_LOCATION = venues.ID
WHERE
    events.id = ".$id) or die(mysql_error());

A: I guess there's a column id in table events, too? If so, the name is ambiguous, because MySQL won't know if you're talking about events.id or venues.id. It doesn't matter you didn't name it as one of the columns to be selected. It exists in more than one table, so you have to tell it which one you actually want.

A: You did not specify for query to use id from which table, and both tables have column name "id" so, it throws the error of "Column 'id' in where clause is ambiguous". so, change your query by putting the table name with id in where clause.
Put either WHERE events.id = ... or WHERE venues.id = ...

A: If a column name is not unique to a single table, then it must be qualified with the table name (or the table alias if appropriate). So, apparently id appears in both tables. From the description, it sounds as if venues was the added table, so (guessing here) you probably need to qualify it as events.id in the WHERE clause.

A: So today I experienced this error as I was building an SQL builder class for my WordPress Plugins. As I tried to execute queries like this;
SELECT ID,post_author,user_login,post_title,user_login,user_email FROM wp_users INNER JOIN wp_posts USING (post_title)

I was getting errors about ID been ambiguous so I made some research and found out the problem.
The two tables I was trying to join all have a column called ID, and since I did not specify the particular column, MYSQL was confused on which table I want to select from.
So once I replaced the ID with wp_post.ID or wp_users.ID, the error was gone.


text:
Q: como puedo sumar todos los valores iguales en Javascript
necesito Transformar este objeto a el que sigue en Javascript

//Original
[
  { word: 'form', value: 4 },
  { word: 'form', value: 4 },
  { word: 'default', value: 4 },
  { word: 'default', value: 30 },
  { word: 'default', value: 31 },
  { word: '[None]', value: 11 },
  { word: '2.- Imagen_1', value: 4 },
  { word: '2.- Imagen_1', value: 3 },
  { word: '2.- Andres_1', value: 22 },
  { word: '1.- Guardar información_0', value: 4 },
  { word: '1.- Guardar información_0', value: 4 }
]

//Transformado

[
  { word: 'form', value: 8},
  { word: 'default', value: 65 },
  { word: '[None]', value: 11 },
  { word: '2.- Andres_1', value: 22 },
  { word: '1.- Guardar información_0', value: 8 }
]

eh intentado de varias maneras, como un for que que suma el valor siguente con el anterior, pero solo suma 2 iguales y al querer volver a usar el ciclo manda que el valor es indefinido

A:

const data = [
    { word: 'form', value: 4 },
    { word: 'form', value: 4 },
    { word: 'default', value: 4 },
    { word: 'default', value: 30 },
    { word: 'default', value: 31 },
    { word: '[None]', value: 11 },
    { word: '2.- Imagen_1', value: 4 },
    { word: '2.- Imagen_1', value: 3 },
    { word: '2.- Andres_1', value: 22 },
    { word: '1.- Guardar información_0', value: 4 },
    { word: '1.- Guardar información_0', value: 4 }
]

const claves = []

//Agregamos todas las claves al arreglo sin repetición
data.forEach(item => {
    if (!claves.includes(item.word)){
        claves.push(item.word)
    }
})

//Por cada clave...
const res = claves.map(clave => ({
    word: clave,
    value: (
        data.filter(item => item.word === clave) //Obtenemos todos los elementos con esa propiedad word
        .reduce((sum, item) => sum + item.value, 0) //Obtenemos la suma de todos sus values
    )
}))

console.log(res)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compiling libxsmm on Macbook air m1 I tried to compile the libxsmm library on my Macbook air m1 (arm64) using the following commands:
git clone --branch 1.17 https://github.com/hfp/libxsmm
cd libxsmm
make generator
cp bin/libxsmm_gemm_generator $HOME/bin
cd ..

However, I got an error that an Intel Architecture or compatible CPU required:
(base) yonatan@Yonatans-MacBook-Air libxsmm % make generator
cc  -DNDEBUG -D__STATIC=1 -DLIBXSMM_BUILD=1  -Iinclude -I./src  -fPIC -Wno-pass-failed -Wall -O2 -pthread  -c ./src/libxsmm_generator_gemm_driver.c -o  obj/intel64/libxsmm_generator_gemm_driver.o
In file included from ./src/libxsmm_generator_gemm_driver.c:11:
In file included from include/libxsmm.h:44:
In file included from include/libxsmm_dnn_convolution.h:14:
In file included from include/libxsmm_dnn.h:14:
In file included from include/libxsmm_typedefs.h:14:
include/libxsmm_macros.h:61:5: error: Intel Architecture or compatible CPU required!
#   error Intel Architecture or compatible CPU required!
    ^
1 error generated.
make: [obj/intel64/libxsmm_generator_gemm_driver.o] Error 1 (ignored)
--------------------------------------------------------------
In case of assembler error, perhaps GNU Binutils are outdated.
See https://github.com/hfp/libxsmm#outdated-binutils
--------------------------------------------------------------
make: *** [obj/intel64/libxsmm_generator_gemm_driver.o] Error 1
(base) yonatan@Yonatans-MacBook-Air libxsmm %

Is there any way to compile or install the libxsmm library on my Mac? I need this library to set up the SeiSol platform (see: documentation https://seissol.readthedocs.io/en/latest/compilation.html) for my studies.
Let me know if any further details are needed. Thanks!


text:
Q: Replicate the go back function of google chrome I am trying to learn how to replicate the go back function of google chrome where it will send you back to the specific page that you went to.
Here is my case:
This is the main page
www.mysite.com/main

Now the main page can have a different types of url here is an example:

*

*www.mysite.com/main/type

*www.mysite.com/main/type/pagenum

*www.mysite.com/main/type/category/pagenum
Now, for example the user visited this url: www.mysite.com/main/dog/labrador/3
And then when the user tried to view the link like this(www.mysite.com/view/title-of-the-link), I will have a go back link button that returns the user to the www.mysite.com/main/dog/labrador/3
I have one solution to solve this using $_SESSION variable, for example:
if($_GET['type']) {
   $sess_type = '/' . $_GET['type'];
}

if($_GET['category']) {
   $sess_cat = '/' . $_GET['category'];
}

if($_GET['pagenum']) {
   $sess_page = '/' . $_GET['pagenum'];
}

$_SESSION['link'] = '/main' . $sess_type . $sess_cat . $sess_page;

This does job a job, I tried to do this idea in my localhost. But I encounter a problem, and that is, for example:
If the last $_SESSION['link'] is -> www.mysite.com/main/cat/persian/5 and then the user tried to view again their previous visits from the history. And they re-visited a link like this, for example www.mysite.com/view/labrador-is-the-title. Then the $_SESSSION['link'] that will save on the go back button will be  www.mysite.com/main/cat/persian/5. That is the problem that I saw on my solution.
My question is, how can I make this properly ? Any suggestion and advices will help me a lot!

A: First of all you should probably use Javascript for the same. It has a History api that you can use. Now assuming that you want to do this in php itself, you should have a little idea on how exactly the back button works in a browser. It is based on a stack that stores all the urls. Here is a little code to get you started
Call the following code before each php script
<?php
  array_push($_SESSION["session_stack"],$_SERVER['REQUEST_URI']);
?>

Call the following code to go back to last page
<?php
  $url = array_pop($_SESSION["session_stack"]);
  header('Location: '.$url);
?>

Basically this maintains a stack on server side similar to browser. When you call the second part of code it simply redirects to last element on the stack.


text:
Q: How to do basic dependency injection in Python (for mocking/testing purposes) Python is a relatively new language for me. Unit Testing and Dependency Injection are something that I've been doing for a little while now, so I'm familiar with it from a C# perspective.
Recently, I wrote this piece of Python code:

import requests  # my dependency: http://docs.python-requests.org/en/latest/

class someClass:
    def __init__(self):
        pass

    def __do(self, url, datagram):
        return requests.post(self, url, datagram)

And then I realized that I had just created a hard-coded dependency. Bleh.
I had considered changing my code to do "Constructor" Dependency Injection:
def __init__(self,requestLib=requests):
    self.__request = requestLib

def __do(self, url, datagram):
    return self.__request.post(self, url, datagram)

This now allows me to inject a fake/mock dependency for the sake of Unit Testing, but wasn't sure if this was considered Python-ic. So I'm appealing to the Python community for guidance.
What are some examples of Python-ic ways to do basic DI (mostly for the sake of writing Unit Tests that utilize Mocks/Fakes)?
ADDENDUM For anyone curious about the Mock answer, I decided to ask a separate question here: How does @mock.patch know which parameter to use for each mock object?

A: While injecting the requests module can be a bit too much, it is a very good practice to have some dependencies as injectable.
After years using Python without any DI autowiring framework and Java with Spring I've come to realize that plain simple Python code often doesn't need a framework for dependency injection with autowiring (autowiring is what Guice and Spring both do in Java), i.e., just doing something like this may be enough:
def foo(dep = None):  # great for unit testing!
    ...

This is pure dependency injection (quite simple) but without magical frameworks for automatically injecting them for you. The caller has to instantiate the dependency or you can do it like this:
def __init__(self, dep = None):
    self.dep = dep or Dep()

As you go for bigger applications this approach won't cut it though. For that I've come up with injectable a micro-framework that wouldn't feel non-pythonic and yet would provide first class dependency injection autowiring.
Under the motto Dependency Injection for Humans™ this is what it looks like:
# some_service.py
class SomeService:
    @autowired
    def __init__(
        self,
        database: Autowired(Database),
        message_brokers: Autowired(List[Broker]),
    ):
        pending = database.retrieve_pending_messages()
        for broker in message_brokers:
            broker.send_pending(pending)

# database.py
@injectable
class Database:
    ...

# message_broker.py
class MessageBroker(ABC):
    def send_pending(messages):
        ...

# kafka_producer.py
@injectable
class KafkaProducer(MessageBroker):
    ...

# sqs_producer.py
@injectable
class SQSProducer(MessageBroker):
    ...

A: Don't do that. Just import requests as normal and use them as normal. Passing libraries as arguments to your constructors is a fun thing to do, but not very pythonic and unnecessary for your purposes. To mock things in unit tests, use mock library. In python 3 it is built into the standard library
https://docs.python.org/3.4/library/unittest.mock.html
And in python 2 you need to install it separately
https://pypi.python.org/pypi/mock
Your test code would look something like this (using python 3 version)
from unittest import TestCase
from unittest.mock import patch

class MyTest(TestCase):
    @patch("mymodule.requests.post")
    def test_my_code(self, mock_post):
        # ... do my thing here...


text:
Q: Surjectivity of polynomials Show that the mapping $f$:[$0,\infty$]$-R$ given $f(x)=x^2+2x-8$ for all $x$ belonging to [$0,\infty$) is invective but not surjective.
How do you prove the surjectivity part?
Because the general method is to suppose that $y$ is the codomain and then show that there exists an $x$ in the source so that $f(x)=y$. This usually involves solving the equation. However, it is not really applicable in the case when have to prove that for polynomials.

A: Note that $f(x)=x^2+2x-8=(x+1)^2-9\ge -9$.
So, it is injective since it is an increasing function on $(-1,\infty)$.
Take $y=-10$, then you will never have $f(x)=-10$ since $f(x)\ge -9$.

A: The injectivity part is fairly easy because $f$ is increasing on the interval $[0, \infty)$.
For surjectivity, note that, since $f$ is increasing on the interval $[0, \infty)$, the minimum of $f$ on that interval must be $f(0) = -8$.

A: The equation
$$x^2+2x-8=y$$
has no real solutions if
$$y<\min\{x^2+2x-8\}=\cdots$$

A: The injectivity is easy: you have to check that for $x,y\in [0,\infty)$ with $x\neq y$ it holds $f(x)\neq f(y)$. This is true because the polynomial (a parabola), has its minimum at $x=-1$, hence it is monotone increasing in $[0,\infty)$.
The surjectivity is also easy: you should exhibit a point in the co-domain, actually the Whole $\mathbb{R}$, that is not coming from a point of the domain. In mathematics, if there exists $y\in\mathbb{R}$ s.t. there exists $x$ in the domain of $f$ s.t. $f(x)\neq y$. And this is true if you get any $y$ below the minimum of $f$, thus any real number strictly less than $f(-1)$. To be more precise, any point in the interval $[f(-1),f(0))$ is also sufficient.


text:
Q: How can I test the update path for my Windows 8 app? When I develop for Windows Phone, I am able to side load the current version of the app (version on the Windows Store) and then run the app in development in the same emulator. This give me an idea if the app update work.
I am trying to do the same thing with Windows 8 App but it doesn't work. I side load the current version of the app and then run the app in development and I get the following message: "The app ... is already installed on this machine".
How can I test the update path for my Windows 8 app?
Thanks!

A: When you build an app from the Windows Store it gets packed up into a an .appx file, which, you can submit for certification or side load using the PowerShell script.
When you run it in a development environment (pressing "play" in Visual Studio) it installs an unpackaged version in a different directory. What this means is that you must remove the packaged  version before you can install the unpackaged one.
However, you can build a package and side load that one, as long as the version number is larger than the one already installed:

*

*In Visual Studio, right click on your project and select "Store" and then "Create App packages...". When asked if you need to build the package for upload to the Windows Store, select "No".

*Choose an output location and enter a version number higher than the one of the currently installed version

*Wait for the project to build.

*Start Windows PowerShell from the start screen, and navigate to the output directory from the above step

*Navigate to the sub directory for the correct build of your app (eg. "MyApp_1.0.1_x64_Debug")

*Run .\Add-AppDevPackage.ps1 and wait for the app to install.

This will have upgraded your current packaged install to the new version, which will allow you to test that any upgrade code in your app works, you will not, however be able to debug it in Visual Studio.
Note, that when your done testing, you should use the remove-appxpackage <Your app ID> (Documentation) PowerShell command to uninstall the side loaded version to prevent you from having issues if you try and install a version from the Windows Store.
Hope that's helpful.
-Andy.
Update: I forgot to mention, you may have to run Set-ExecutionPolicy RemoteSigned from an admin PowerShell window before you are able to execute .ps1 scripts - http://technet.microsoft.com/en-us/library/hh849812.aspx


text:
Q: Pandas replace column value under condition I have the following dataframe:
df = pd.DataFrame({'A' : [1., 2., 3., 4.], 'B' : [4., 3., 2., 1.], 'C' : [pd.NaT,8,pd.NaT,0]})
df

And I would like to change the column B to the value of C everytime that C is different from NaT. The final result would be the following:

A: Use combine_first:
df['B'] = df['C'].combine_first(df['B'])
print (df)
     A  B    C
0  1.0  4  NaT
1  2.0  8    8
2  3.0  2  NaT
3  4.0  0    0

And if need floats:
df['B'] = df['C'].combine_first(df['B']).astype(df['B'].dtype)
print (df)
     A    B    C
0  1.0  4.0  NaT
1  2.0  8.0    8
2  3.0  2.0  NaT
3  4.0  0.0    0

Or mask with notnull:
df['B'] = df['B'].mask(df['C'].notnull(), df['C'])
print (df)
     A  B    C
0  1.0  4  NaT
1  2.0  8    8
2  3.0  2  NaT
3  4.0  0    0

Or numpy.where:
df['B'] = np.where(df['C'].notnull(), df['C'], df['B'])
print (df)
     A  B    C
0  1.0  4  NaT
1  2.0  8    8
2  3.0  2  NaT
3  4.0  0    0

A: pd.Series.fillna
df.B = df.C.fillna(df.B)
df

     A    B    C
0  1.0  4.0  NaT
1  2.0  8.0    8
2  3.0  2.0  NaT
3  4.0  0.0    0

pd.DataFrame.where
df.B = df.B.where(df.C.isnull(), df.C).astype(df.B.dtype)
df

     A    B    C
0  1.0  4.0  NaT
1  2.0  8.0    8
2  3.0  2.0  NaT
3  4.0  0.0    0


text:
Q: Android: How to add existing JSONObject to existing key I have a data structure like this:
source: {
    property_1: String,
    property_2: String,
    property_3: {
        property_31: String
    }
}

I want to have a function like this:
private JSONObject mergeProperty(JSONObject source, String propertyName, JSONObject newData)

in which, source is data above, propertyName = "property_3", and
newData: {
    property_32: String,
    property_33: int
}

with result of calling mergeProperty(source, "property_3", newData) as:
output: {
    property_1: String,
    property_2: String,
    property_3: {
        property_31: String,
        property_32: String,
        property_33: int
    }
}

Is there any simple method to achieve this without having to map the JSON object to HashMap first? I found no built-in JSONObject function which corelates to my problem.

A: If I got your intention right, this code must do the job. Please, note, that this will mutate original source, so you might need to pass a copy, if mutating original one is not what you want. Also, here I assume that propertyName is on the first level of your source JSON, and is JSON, too, else this will throw a JSONException.
JSONObject mergeTarget = source.getJSONObject(propertyName);
Iterator<String> keys = newData.keys();

while (keys.hasNext()) {
    String key = keys.next();
    mergeTarget.put(key, newData.get(key));
}

A: Try accumulate method of org.json.JSONObject.
Below code may be useful to you.
public class Test {

    public static void main(String[] args){
        System.out.println("test");
        JSONObject source = new JSONObject("{\"property_1\":\"String\",\"property_2\":\"String\",\"property_3\":{\"property_31\":\"String\"}}");
        JSONObject newData = new JSONObject("{\"property_32\":\"String\",\"property_33\":\"int\"}");
        System.out.println("Before merge :"+source.toString());
        mergeProperty(source, "property_3", newData);
        System.out.println("After merge :"+source.toString());
    }

    private static void mergeProperty(JSONObject source, String property, JSONObject newData){
        for (Object key : newData.keySet()){
            String keyStr = (String)key;
            Object keyvalue = newData.get(keyStr);
            source.getJSONObject(property).accumulate(keyStr , keyvalue);
        }
    }
}


text:
Q: Spring Boot & Liquibase by Example Spring Boot and MySQL here. Trying to get my Spring Boot app to use Liquibase for my DB migrations and see in the docs that Spring Boot has built-in support for Liquibase.
However after reading those docs, I'm left with several related concerns:

*

*What is the fundamental purpose of the db/changelog/db.changelog-master.yaml file? Is it to store Liquibase configurations (that dictate how Liquibase behaves), or is that where I'm supposed to put the actual, sequential SQL changes (the "migrations") themselves?

*

*Ideally I'd like to have a src/main/resources/migrations directory and store my migration changes as individual SQL files, like so:

*src/main/resources/migrations/001-schema.sql

*src/main/resources/migrations/002-init.sql

*src/main/resources/migrations/003-changing-account-types.sql

*...etc. Is it possible to configure Liquibase to do this via Spring Boot?

*When will Spring Boot run these Liquibase migrations? At app startup? What if the Spring Boot app actually runs on a cluster of nodes (say 5 nodes behind a load-balanced URL)? Will Spring Boot run Liquibase run 5 times, once on each node? Or does it somehow sense that one node is the "master migrator", etc.?

A: The db/changelog/db.changelog-master.yaml file is the one executed on application startup when using default configuration. In that file you can have the sequential SQL changes as well as inclusions to other files. For example the file could contain inclusions like this (xml syntax)
<include file="migrations/001-schema.sql"/>
<include file="migrations/002-init.sql"/>
<include file="migrations/003-changing-account-types.sql"/>

and you would have the configuration you wanted.
About your second question - yes, they are applied at startup. If it runs on a cluster of nodes, they will each check the status and apply the changes to database if they aren't already applied(the databasechangelog and databasechangelock tables are used for that and they make sure the changes are only applied once)
example for yaml syntax
databaseChangeLog:
- include:
    file: migrations/001-schema.sql
- include:
    file: migrations/002-init.sql
- include:
    file: migrations/003-changing-account-types.sql


text:
Q: MySQL id numbering in table Let's say that I have a table linked to a database like this: http://www.falkencreative.com/forum/records/view.php
How do I make it so that when I delete a record and then add a new one, the new replaces the previously deleted record and has the previously deleted id number instead of the next id?
For example

*

*Red

*Blue

*Green

click button to delete green.

*

*Red

*Blue

click button to add new color.
input orange

*

*Red

*Blue

*Orange

As it stands, what I'm working with is putting out:
1. Red
2. Blue
4. Orange (What should set this to 3?)
It's probably something simple in terms of the table set up, but I have no idea what to do and I'm pressed for time. Can anyone guide me on what I should do?

A: You may have 2 options. Either update the same row where the "Green" value was previously. i.e.:
mysql_query("UPDATE table_name SET color = 'orange' WHERE ID = '3'");

or
mysql_query("UPDATE table_name SET color = 'orange' WHERE color = 'green'");

or
whatever your specifiers could be.
this should be from the MySql standpoint the easiest way. Or you can delete it as you initially outlined and re insert new row with mysql_query("INSERT INTO .... but then MySql PK UID will need to be reset i.e.:
mysql_query("ALTER TABLE table_name AUTO_INCREMENT = 1");

which will remove your used PK IDs and renumbers all rows.  Or is there an easier solution ?

A: I think you want to UPDATE the record, rather than DELETE the old and INSERT a new one.
Edit:
If you want to insert a new record and assign it the next sequential id, use a non-auto_increment column and do this when adding a new record:
INSERT INTO myTable (id, ...) VALUES ( (SELECT MAX(id) + 1 FROM myTable), ...)

I don't have a database handy to test this, but I think it will work.  But I'm not sure what will happen when the table is empty. Also this may create a race condition.

A: No, when you delete a database row, if the column have the AUTO_INCREMENT active, it will take the value from a sequence.
If you delete 3, the sequence always start from 3+1.
You can see\set the auto-increment value for example from php myadmin.
I don't know what DBMS are you using, but with oracle you can manipulate the sequence.
So you have various way.

*

*Complicated: When you insert\delete you update the sequence with the triggers

*You use 3 coloumn: id, IdToShow, Value.

id is the same of now, you use it with autoinc.
idToShow also is what you show. When you insert you can insert it counting the rows present in the table (you have various ways).
Hope it help.

A: Your problem is not about database IDs, it's about not understanding the difference between an ID and a line number. They have nothing to do with each other. Just simply output the loop counter ("$i") instead of the ID.
<?php
for ($i = 1; $i <= foo(); $i++) {
    print "
{$i}	...
\n";
}
?>


text:
Q: Assign explicit version to existing rows of the table I have a table where records are inserted and updated. In case of updates, a new row is inserted into the table. In order to track updates for a given record, there's a column added to the table called root_record_id which holds the id of the very first record in the update chain.
For eg: Consider the record table schema as follows:

id
root_record_id
other columns

1
1
...

2
2
...

3
1
...

4
1
...

5
2
...

In this case, a record with id=1 was inserted, which was then updated to id=3 and then to id=4. Similarly the record with id=2 was inserted and then updated to id=5.
I want to add a version column to this table, where version is incremented on each update and starts with 0.

id
root_record_id
version
other columns

1
1
0
...

2
2
0
...

3
1
1
...

4
1
2
...

5
2
1
...

I tried writing queries using group by clause on root_record_id but failed to accomplish the task.

A: DBFIDDLE
This query produces the version that you can use (in an update, or in a trigger):
SELECT
    id,
    root_record_id,
    RANK() OVER (partition by root_record_id ORDER BY id ASC)-1 version
FROM table1
ORDER BY id;

output:

id
root_record_id
version

1
1
0

2
2
0

3
1
1

4
1
2

5
2
1

A: If you are looking for the general sequence on how to add the column and then pre-fill the values, then follow this fiddle: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5a04b49fbda3883a9605f5482e252a1b

*

*Add the version column allowing nulls:
ALTER TABLE Records ADD version int null;

*Update the version according to your logic:
UPDATE Records
SET version = lkp.version
FROM Records r
INNER JOIN (
    SELECT Id, COUNT(root_record_id) OVER (partition by root_record_id ORDER BY id ASC)-1 as version
    FROM Records
) lkp ON r.Id = lkp.Id;

*Alter the version column to NOT allow nulls
ALTER TABLE Records ALTER COLUMN version int not null;

*Finally, ensure that you increment the version column during new row inserts.


text:
Q: Как открывать файл с помощью кнопки Unity2D Как открывать файл по кнопке?
К примеру, я создал программу и хочу что бы при нажатии на кнопку, открывалась программа на компьютере, или фотка с папки куда я закинул вместе с программой.


text:
Q: Retrieve Selected Points from ggplotly in Another Part of Shiny App Desired Outcome
I would like to be able to click a point in my plotly::ggplotly() graph within my {shiny} app and then display some info about that point in a separate output below.
MRE
In this simple example I can make it display the curveNumber, pointNumber, x, y, but it's not easy to unambiguously retrieve a particular data point from my original data from these values. I've read about using key within the plotly::renderPlotly() call although I'm not sure how I'd access that in a separate part of the app.
library(tidyverse)
library(plotly)
library(shiny)

# UI  ----
ui <- fluidPage(plotlyOutput("plot"),
                verbatimTextOutput("click"))

# server  ----
server <- function(input, output) {
  output$plot <- renderPlotly({

    p <- mtcars %>%
      rownames_to_column("car") %>%
      ggplot(aes(x = disp, y = mpg, color = factor(cyl),
                 label = car)) +
      geom_point(size = 4, alpha = 0.7)

    ggplotly(p) %>%
      event_register("plotly_click")
  })

  output$click <- renderPrint({
    point <- event_data(event = "plotly_click", priority = "event")
    if (is.null(point)) "No Point Selected" else point
  })
}

# app ----
shinyApp(ui = ui, server = server)

A: Using code from here I figured out how to use key to identify the points and then retrieve that elsewhere from the event_data().
library(tidyverse)
library(plotly)
library(shiny)

d <-  mtcars %>%
  rownames_to_column("car")

# UI  ----
ui <- fluidPage(plotlyOutput("plot"),
                tableOutput("click"))

# server  ----
server <- function(input, output) {
  output$plot <- renderPlotly({

    key <- d$car

    p <- d %>%
      ggplot(aes(x = disp, y = mpg, color = factor(cyl),
                 key = key)) +
      geom_point(size = 4, alpha = 0.7)

    ggplotly(p) %>%
      event_register("plotly_click")
  })

  output$click <- renderTable({
    point <- event_data(event = "plotly_click", priority = "event")
    req(point) # to avoid error if no point is clicked
    filter(d, car == point$key) # use the key to find selected point
  })
}

# app ----
shinyApp(ui = ui, server = server)


text:
Q: Dotnet Apache Spark - Object reference not set to an instance of an object I've been trying to register and run a UDF with dotnet apache spark. I am using Microsoft.Spark.0.10.0 on MacOs
This is what I've been trying to do
var options = new Dictionary<string, string>
            {
                {"delimiter", "|" }
            };

            var schema = "Username STRING, Machine STRING, Date STRING";

            var df = spark
                .Read()
                .Format("csv")
                .Options(options)
                .Schema(schema)
                .Load(staff);

            df.PrintSchema();
            df.Show();

            spark.Udf().Register<string, string>("MyUDF", randomFunc);

            df.CreateOrReplaceTempView("AllLogs");

            DataFrame dateDf = spark.Sql("SELECT *, MyUDF(alllogs.Username) FROM AllLogs");
            dateDf.Collect();

And random func is
        private static string randomFunc(string val)
        {
            return "Random";
        }

I keep seem to be getting the same error. I've tried different ways of creating Udf's, but none of them seem to be working.
This is the error:
[Error] [TaskRunner] [1] ProcessStream() failed with exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Spark.Utils.UdfSerDe.Deserialize(UdfData udfData) in /_/src/csharp/Microsoft.Spark/Utils/UdfSerDe.cs:line 168
   at Microsoft.Spark.Utils.CommandSerDe.DeserializeUdfs[T](UdfWrapperData data, Int32& nodeIndex, Int32& udfIndex) in /_/src/csharp/Microsoft.Spark/Utils/CommandSerDe.cs:line 267
   at Microsoft.Spark.Utils.CommandSerDe.Deserialize[T](Stream stream, SerializedMode& serializerMode, SerializedMode& deserializerMode, String& runMode) in /_/src/csharp/Microsoft.Spark/Utils/CommandSerDe.cs:line 243
   at Microsoft.Spark.Worker.Processor.CommandProcessor.ReadSqlCommands(PythonEvalType evalType, Stream stream) in D:\a\1\s\src\csharp\Microsoft.Spark.Worker\Processor\CommandProcessor.cs:line 190
   at Microsoft.Spark.Worker.Processor.CommandProcessor.ReadSqlCommands(PythonEvalType evalType, Stream stream, Version version) in D:\a\1\s\src\csharp\Microsoft.Spark.Worker\Processor\CommandProcessor.cs:line 117
   at Microsoft.Spark.Worker.Processor.CommandProcessor.Process(Stream stream) in D:\a\1\s\src\csharp\Microsoft.Spark.Worker\Processor\CommandProcessor.cs:line 62
   at Microsoft.Spark.Worker.Processor.PayloadProcessor.Process(Stream stream) in D:\a\1\s\src\csharp\Microsoft.Spark.Worker\Processor\PayloadProcessor.cs:line 74


text:
Q: Database for big records What is the best database for storing big chunks of data? I want to store the following stucture:
| batch_id (int, key) | part_number (int, key) | chunk (blob, around 5MB) |
There might be thousands of that records. I thought about some NoSQL solutions. Maybe MongoDB? It's also nice to have nicely supported Java connection driver for this database.

A: I suggest you store blobs as files in the file system, and store paths in the database.


text:
Q: htaccess rewrite from page ID to name not working I'm calling ?page=about using the GET method in a form on index.php (ie. 'about' is a select option). Once I click submit, the URL will look like this:
http://example.com/?page=about
However I would like it to look like this instead:
http://example.com/about
but keep the script (PHP) working on index.php (do don't and don't want to have an 'about' file), ie. I would like to make use of the GET values on the same page once the form is sent. I can make the php script work, it reacts fine, but the URL rewriting does not work at all.
I have tried the following htaccess rewrite, but it doesn't do anything, the URL remains as above.
My htaccess:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?page=$1 [L,QSA]

I would greatly appreciate your help, as I have no idea why this isn't working. I have searched through the net, and everyone points to this rule, yet it just doesn't do any thing at all for me.
Thanks a lot in advance!
EDIT:
Let me post my php code I use, sorry, I missed that. I have removed the action attribute for now as I'm using it in a browser that I know is sending me to the same when submitting the form:
<?php

$page = $_GET['page'];

switch($page){
 case 'about': echo 'I am me'; break;
 case 'galery': echo 'Nice pictures here'; break;
}

?>

<body>

<form action="/" method="get">
<select name="page">
    <option value="about">about</option>
    <option value="galery">galery</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>

EDIT #2:
I had to add action="/" to the form tag in order anubhava's solution to work.

A: This should be your complete .htaccess:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

#external redirect from /?page=about OR /index.php?page=about to /about
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php|)\?page=([^\s]+) [NC]
RewriteRule ^ /%1? [R=301,L]

#internal forward from /about to /?page=about
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+?)/?$ /?page=$1 [L,QSA]

A: Try
 ...
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

And

I'm calling ?page=about using the GET method in a form on index.php

Try calling the right link? '/about' instead of '?page=about'


text:
Q: Read multiple hash keys and keep only unique values If I have data in Hiera like:
resource_adapter_instances:
  'Adp1':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'Plan_DB.xml'
  'Adp2':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'ODB_Plan_DB.xml'
  'Adp3':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'Plan_DB.xml'

And I need to transform this into an array like this, noting duplicates are removed:
[/opt/weblogic/middleware/Plan_DB.xml, /opt/weblogic/middleware/ODB_Plan_DB.xml]

I know I have to use Puppet's map but I am really struggling with it.
I tried this:
$resource_adapter_instances = hiera('resource_adapter_instances', {})
$resource_adapter_paths = $resource_adapter_instances.map |$h|{$h['adapter_plan_dir']},{$h['adapter_plan']}.join('/').uniq
notice($resource_adapter_instances)

But that doesn't work, and emits syntax errors. How do I do this?

A: You are on the right track. A possible solution is as follows:
$resource_adapter_instances = lookup('resource_adapter_instances', {})
$resource_adapter_paths =
  $resource_adapter_instances.map |$x| {
    [$x[1]['adapter_plan_dir'], $x[1]['adapter_plan']].join('/')
  }
  .unique
notice($resource_adapter_paths)

A few further notes:

*

*The hiera function is deprecated so I rewrote using lookup and you should too.

*Puppet's map function can be a little confusing - especially if you need to iterate with it through a nested Hash, as in your case. On each iteration, Puppet passes each key and value pair as an array in the form [key, value]. Thus, $x[0] gets your Hash key (Adp1 etc) and $x[1] gets the data on the right hand side.

*Puppet's unique function is not uniq as in Bash, Ruby etc but actually is spelt out as unique.

*Note I've rewritten it without the massively long lines. It's much easier to read.
If you puppet apply that you'll get:
Notice: Scope(Class[main]): [/opt/weblogic/middleware/Plan_DB.xml,
  /opt/weblogic/middleware/ODB_Plan_DB.xml]


text:
Q: SQL Server: If a row is inserted in one table, how do I write a trigger to insert that same row in a different table? I'm not sure how to create this trigger,.I need to add a row in pub_info table when a row is inserted in publishers table. The exact same row. SQL server
CREATE TRIGGER checkCity
ON pub_info
AFTER INSERT
AS
IF -- a row is inserted into publishers table,
   -- how do I add the same row into pub_info table?
INSERT VALUES(@pub_id, NULL, 'new publishers')
BEGIN
END;

A: You have to create a trigger on publishers table and not on pub_info .
The inserted data is available in the INSERTED table in the trigger
CREATE TRIGGER checkCity
ON publishers
AFTER INSERT
AS
BEGIN
  INSERT INTO pub_info(pubid, pubname, pub_description)
      SELECT pubid, pubname, pub_description
      FROM INSERTED;
END;


text:
Q: Посоветуйте мануал по регулярным выражениям Пишу парсер, регулярные не знаю вообще.
Очень нужно кратко, быстро, ясно. Ну не статью в интернете (хотя если хорошая - шлите), и не три тома. Надеюсь, Вы поняли меня).
A: Есть книжка Фридл Д. Регулярные выражения. Там около 550 стр.
Если совсем кратко, то, помню, в книжке Шварц, Феникс и фон Брайан. Изучаем Perl была достаточно краткая и очень хорошая глава по регуляркам. Но там все, естественно, на перле.
A: Regular Expressions: A Brief Tutorial
by Dorothea Salo
Мануал с подробным пояснением и заданиями


text:
Q: Regex in java to check for double consonant I want to write a regex in Java to check if a string ends in double consonant.
My regex is not working.
\\w+[^aeiou]\\1$

Appreciate your help
Thanks a ton.

A: It doesn't work since \1 references a non-existent subpattern. You need to assign a capturing group. Capturing groups could be used later on in the regular expression as a backreference to what was matched in that captured group.
\\w+([^aeiou])\\1$

Based off the comment above about your regular expression not only matching double consonants, I would consider combining an intersection with negation to make sure the grouped character is an actual letter character.
(?i)\\w+([a-z&&[^aeiou]])\\1$

A: This might work.
 # "(?i)\\w+(?:(?![aeiou])[a-z]){2}$"

 (?i)                # Case independent
 \w+
 (?:
      (?! [aeiou] )  # Not a vowel ahead
      [a-z]          # Consonant only
 ){2}
 $


text:
Q: C# - is there any difference between x.ToString("D") and x.ToString(), where x is type int? My personal preference is x.ToString(), since it has slightly fewer letters. Is there any advantage to either one?

A: The main point of .ToString("D") is that it allows you to specify the preceding number of digits.
e.g,
var i = 123;

var stringed = i.ToString("D5");//stringed = 00123

A: Take a look at what the "D" actually means here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

"D" or "d"    Decimal Result: Integer digits with optional negative sign.
Supported by: Integral types only.
Precision specifier: Minimum number of digits.
Default precision specifier: Minimum number of digits required.
More information: The Decimal("D") Format Specifier.
1234 ("D") -> 1234
-1234 ("D6") -> -001234

So, depending on the format of the output you're looking for, that's what the different format (or precision) specifiers can help dictate your output.

A: From the Microsoft documentation:

To format an Int32 value as an integral string with no leading zeros, you can call the parameterless ToString() method. By using the "D" format specifier, you can also include a specified number of leading zeros in the string representation.

It would appear that "D" without digits is what Int32.ToString() uses by default.
There is then, no difference in output between the two.

A: Look at this article

The "D" (or decimal) format specifier converts a number to a string of
  decimal digits (0-9), prefixed by a minus sign if the number is
  negative. This format is supported only for integral types.

It shows the same result for the case "D".
But it will pad with zeros to the left of your int if you "Dx" (x is a number)
ToString() is enough for you to convert to string


text:
Q: Changing variable values after method thank you for helping with multiple coding issues in the past but I've stumbled onto one more. I really need some directions on this.
In the script below, I am trying to change the value of b when met1, met2 and met3 are called in the Main function.
    class Class3
{
    public class Storage
    {
        public static int a = 100;
        public static int b = a + 5;
    }
public static void Main()
    {
        Methods Test = new Methods();
        Console.WriteLine("Original a value: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met1();
        Console.WriteLine("After met1: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met2();
        Console.WriteLine("After met2: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
        Test.Met3();
        Console.WriteLine("After met3: {0}", Storage.a);
        Console.WriteLine("b value: {0}", Storage.b);
    }
    public class Methods
    {
        public void Met1()
        {
            Storage.a -= 10;
        }
        public void Met2()
        {
            Storage.a -= 10;
        }
        public void Met3()
        {
            Console.WriteLine("{0}", Storage.a);
            Met1();
            Met2();
            if (Storage.a > 10)
            {
                Met3();
            }
        }
    }
}

From my code above, the value of b stays at 105 even though the value of a changes. From what I can tell from here, variable b was not called again to change its value.
Should I put variable b as a method and call it? This is just an example I did and I have over 50 formulas that require changes whenever one of the variables within the formula changes. I dont think creating 50 over methods is a good idea as there should be a better way of coding this.
Thank you!

A: Fields don't change automatically. That means that b = a + 5 will set b to 105. To re-calculate the value of b every time, you can change it to a property like:
public static int b => a + 5;

This way every time you access b it calculates a + 5.


text:
Q: How to extend the timeout on lucene.net directory lock Directory lock error with Lucene.Net usage in an ASP.NET MVC site
Hi guys,
In the link above essentially is the issue I have.
However I am correctly disposing of the writer.
Problem is my main writer takes 20 mins due to the size of the data (200k + docs 25 Cols) and the slowness of the server.
So I have 2 writers one which does everything (all document on a 4 hour timer)
And one for when someone manually edits a column it removes a document and re adds it.
It is the second one that is throwing the timeout due to the fact that the first writer is still doing its thing taking forever. I would like to increase the timeout is this possible?
Cheers

A: You can change the lock timeout by increasing IndexWriter.WRITE_LOCK_TIMEOUT, or setting it to -1 to wait forever. There's also a Lock.LOCK_POLL_INTERVAL that states how often Lock.Obtain should attempt to retrieve the lock.


text:
Q: How to switch to previous version of mozila using developer tools? I am working on a project, which is under testing now. Need is to make Website compatible with all Modern as well as at-least make them compatible with 2 older versions of every Major browsers.
For this I used IE F12 tools in IE, to Switch to IE 9,8,7 view.
Now is there any Tool for Firefox, Chrome, Safari and Opera, which let me switch to its previous version for testing?

A: There isn't - you need to install different versions of the browsers. This is absolutely unproblematic with Firefox, just specify a different installation path for the old version (note that only one Firefox instance can run at a time unless you create different profiles and use -no-remote command line flag). I think that it is similar with Safari and Opera. Chrome is complicated however, you simply cannot install a version older than the current release - with some luck you can find it on PortableApps.com (it will be slightly broken). You can have Chrome versions from different channels (e.g. Release and Beta) but you have to install them under different user accounts.


text:
Q: default surefire not executing the test with Spring Boot I am working on a quite simple Spring Boot 2.4.2 project, using the BOM :
  <dependency>
    <!-- Import dependency management from Spring Boot -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.2</version>
    <type>pom</type>
    <scope>import</scope>
  </dependency>
</dependencies>

when running mvn clean verify, I get this : we see that no test is found by Surefire 2.12.4
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ api-testing ---
[INFO] Surefire report directory: C:\Users\vincent\IdeaProjects\api-testing\target\surefire-reports

-------------------------------------------------------  T E S T S
-------------------------------------------------------

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

I don't understand why.. I tried several things, and even if it's not recommended, I tried overriding the version by adding this in my pom :
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.22.2</version>
    </plugin>
  </plugins>
</build>

And now my test is found !
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ api-testing ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running de.vincent.AssetReferentialServiceTest

I am really surprised by this Spring Boot behavior - I assume I am missing something.. but what ?
Note : my test is a Junit 5 test, and I have no Junit 4 related jars in my classpath - only Junit Jupiter 5.7.0 and Junit platform 1.7.0
Thanks

A: Thanks a lot @M. Deinum for pointing out the issue in the comment.
Of course, using Spring Boot parent pom helps a lot in using the proper plugins versions !
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.4.2</version>
</parent>

The BOM will only help for the dependencies, not the build plugins.


text:
Q: desktop built-in VGA port and Nvidia geforce210 for dual monitor I have a problem on my monitor, one monitor is connected to the built-in VGA port and the other one is connected on my video card which is a NVIDIA GeForce210. At first the two monitor work but when I installed the driver for the NVIDIA GeForce210 the monitor connected to the built-in VGA port stopped working (it's not being detected anymore).
When I run xrandr, this is the result:
Screen 0: minimum 8 x 8, current 1366 x 768, maximum 8192 x 8192
DVI-I-0 disconnected (normal left inverted right x axis y axis)
VGA-0 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 413mm x 234mm
   1366x768       59.8*+
   1360x768       60.0
   1024x768       75.0     72.0     70.1     60.0
   800x600        75.0     72.2     60.3     56.2
   640x480        75.0     72.8     59.9
   640x400        70.1
DVI-I-1 disconnected (normal left inverted right x axis y axis)
HDMI-0 disconnected (normal left inverted right x axis y axis)

And sudo lshw -c video:
    Screen 0: minimum 8 x 8, current 1366 x 768, maximum 8192 x 8192
    DVI-I-0 disconnected (normal left inverted right x axis y axis)
    VGA-0 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 413mm x 234mm
       1366x768       59.8*+
       1360x768       60.0
       1024x768       75.0     72.0     70.1     60.0
       800x600        75.0     72.2     60.3     56.2
       640x480        75.0     72.8     59.9
       640x400        70.1
    DVI-I-1 disconnected (normal left inverted right x axis y axis)
    HDMI-0 disconnected (normal left inverted right x axis y axis)

And `sudo lshw -c video`:

*-display
       description: VGA compatible controller
       product: GT218 [GeForce 210]
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a2
       width: 64 bits
       clock: 33MHz
       capabilities: vga_controller bus_master cap_list rom
       configuration: driver=nvidia latency=0
       resources: irq:45 memory:f6000000-f6ffffff memory:e0000000-efffffff memory:f0000000-f1ffffff ioport:e000(size=128) memory:f7000000-f707ffff
  *-display
       description: Display controller
       product: Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 09
       width: 64 bits
       clock: 33MHz
       capabilities: bus_master cap_list
       configuration: driver=i915 latency=0
       resources: irq:43 memory:f7400000-f77fffff memory:d0000000-dfffffff ioport:f000(size=64)


text:
Q: How do I segregate my changes in git branches when I'm not ready to commit? So, I have two git branches, master and testing. I checkout testing. I make some changes that are only halfway done and not ready to even stage let alone commit, I'm just screwing around. If I checkout master again, my screwy changes are included!! What??
So I could accidentally have some bad stuff in master just because it was not good enough to even commit in testing?
I thought branches would segregate my work. I tried staging even and that didn't seem to work. It seemed like I have to actually commit in testing or else my changes will stay visible (but uncommitted) in the files in my master branch.
What am I missing?

A: That's what git-stash is for. You can stash your changes using
git stash

and get them back using
git stash apply

when you are done you should clear your stash using
git stash clear

If you want to just delete your changes you can use
git reset --hard
git clean -fd

Info taken from here.

A: You could simply make a "tmp" branch, and commit in it.
git checkout -b tmp

That way, master, and testing are unchanged.
And you can resume your changes in tmp at any time.


text:
Q: Unable to update JSON field. Shows "JSON parse error - Expecting property name enclosed in double quotes" I am new to Django Rest Framework. I am currently making an API, which will GET the favourite TV shows, and create or update the existing list if more TV shows are made favourite. All of these have a unique account_id. I have to send such a JSON response.
{
  "account_id": "15",
  "shows": [
    {
      "show_id": "19"
    },
    {
      "show_id": "86"
    }
  ]
}

But when i try to PUT such a JSON response,
{
    "account_id": 15,
    "shows": [
    {
        "show_id": "9"
    },
    {
        "show_id": "86"
    }
    ]
}

I get the error,
{
  "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 5 (char 6)"
}

My models.py is:
from django.db import models

class Account(models.Model):
    account_id = models.CharField(max_length=500)

class Show(models.Model):
    show_id = models.CharField(max_length=500)
    user_id = models.ForeignKey(Account, related_name='shows')

My views.py is:
from .models import Show, Account
from showapp.serializers import ShowSerializer, AccountSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view

class UserList(APIView):

    parser_classes = (JSONParser,)

    def get(self, request, format=None):
        users = Account.objects.all()
        serializer = AccountSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = AccountSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        user = self.get_object(pk)
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'PUT'])
def user_detail(request, account_id):

    try:
        user = Account.objects.get(account_id=account_id)
    except Account.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = AccountSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = AccountSerializer(user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

My serializers.py is:
class ShowSerializer(serializers.ModelSerializer):

    class Meta:
        model = Show
        fields = ('show_id',)

class AccountSerializer(serializers.ModelSerializer):

    shows = ShowSerializer(many=True)

    class Meta:
        model = Account
        fields = ('account_id', 'shows')

Please Help me out.


text:
Q: PHP - Convert a string containing a specific numeration into an array I have a string containing a numeration like this:
$string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';

And now I want to convert this string (without any breaks) containing this numeration to an array that contains these items ("Just an example", "Another example", "Just another example" etc).
I cant' just use
$array = explode('.', $string);

because those items can also contain dots and other symbols or numbers like in my fourth item called "Example.mp3". The numeration goes up to about 50, but the amount of items isn't the same every time (sometimes I have just one item, but sometimes I have 2, 3 or even 15 items in this string). It doesn't always start with a 0.
How can I "convert" this string into an array without using the dot as separator but maybe using this whole numberation format and the dot together as a separator?

A: This is definitely not the best solution possible, but as far as I can tell it can handle almost any input pretty well.
<?php
    $string = '01. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';

    $things=explode(' ',$string);
    $num=1;

    $your_output=array();

    foreach($things as $thing)
    {
            $num_padded = str_pad($num, 2, '0', STR_PAD_LEFT) .'.';
            if($num_padded==$thing)
            {
                    $num++;
                    $your_output[$num]='';
            }
            else
                    $your_output[$num].=' ' . $thing;

    }

    $final_result=array();
    foreach($your_output as $k=>$v)
    {
            $final_result[]=trim($v);
    }

    var_dump($final_result);

    ?>

A: Here is another option, I also removed the 0 from the first number.
$string = '1. Just an example 02. Another example 03. Just another example 04. Example.mp3 05. Test 123 06. Just an example again';
// Replace the digit format with an easy delimiter
$string_rep = preg_replace('/(\d{1,}\.\s?)/', '|', $string);
// convert string to an array
$string_arr = explode('|', $string_rep);
// remove empty array entries
$clean = array_filter($string_arr);

print_r($clean);

/*
// result
Array
(
    [1] => Just an example
    [2] => Another example
    [3] => Just another example
    [4] => Example.mp3
    [5] => Test 123
    [6] => Just an example again
)
*/


text:
Q: PHP static property with extending class overwritten Please, could you help me a bit with my problem?
I have class called Translateable and then clasess Article and Banner, which extend this class.
Problem occurs, when I do this:
$article = (new Article)->find(15);
$banner =  (new Banner)->find(1);

$articleTrans = $article->trans(); // method trans is method from Translateable

When I call $article->trans(); I expect output like this:
App\Models\ArticleTrans
Article

but it return this:
App\Models\ArticleTrans
Banner

First row is ok, but the second one if bad and I don't know, how to solve this problem.
I need to have $instance stored as static property.
Could you give me you help?
  class Translateable extends Model {

        static $transLang = null;
        static $transClass = null;
        static $instance = null;

        public function __construct(array $attributes = array()) {

            static::$transLang = App::getLocale();

            parent::$transClass = static::$transClass;
            parent::$instance = static::$instance;
            parent::__construct($attributes);

        }
        /**
         * get items trans
         *
         * @param null $lang
         * @return mixed
         */
         public function trans($lang = null) {
              if($lang == null) {
                 $lang = static::$transLang;
              }

                  echo static::$transClass;
                  echo class_basename(static::$instance);
                  die();

              }
              public static function find($primaryKeyVal, $columns = []) {

                 $tci = new static::$transClass;
                 $item = static::withTrans()->where(static::$instance->getTable() . '.' . static::$instance->primaryKey, '=', $primaryKeyVal)->where($tci->getTable() . '.lang', '=', static::$transLang)->first();
    return $item;

        }
    }

class Article extends Translateable {
        static $transClass = 'App\Models\ArticleTrans';

        public function __construct(array $attributes = array()) {

            parent::$transClass = static::$transClass;
            parent::$instance = $this;

            parent::__construct($attributes);

        }
 }

class Banner extends Translateable {

    static $transClass = 'App\Models\BannerTrans';

    public function __construct(array $attributes = array()) {

        parent::$transClass = static::$transClass;
        parent::$instance = $this;

        parent::__construct($attributes);

    }
}


text:
Q: Object gets unwanted width and height Is it possible to stop WordPress adding a width and height to an object when you pate it in to the source view?
When I paste in
<object data="grid-linked-in.svg" type="image/svg+xml"></object>

WP changes it to
<object width="300" height="150" type="image/svg+xml" data="grid-linked-in.svg"></object>

A: You can try this:
add_filter( 'media_send_to_editor', 'remove_width_height_attribute', 10 );

function remove_width_height_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

A: You can use jQuery for this:
$('object').each(function(){
    $(this).removeAttr('width height');
});

That should remove those attributes for you. You can even set attributes as well if need be. Put the following inside the function above (Obviously you can change the attributes as need be).
$(this).css('max-height',500);


text:
Q: How to call the override pause method dynamically from Libgdx? I create a Libgdx game and I want to know if it is possible to call the override pause method lifecycle with Libgdx?
Here is my pause method lifecycle in my class:
public class MyGdxGame extends ApplicationAdapter {
    @Override
    public void pause() {
        super.pause();
        chrono.pause();
        //Display a pause menu
    }
}

And I want to call the lifecycle method when I click on the pause image:
    imagePause = new Image(new Texture(Gdx.files.internal("pause.png")));
    imagePause.setSize(pauseSize, pauseSize);
    imagePause.setPosition(width - pauseSize, height - pauseSize);
    imagePause.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            //Something like this? :
            Gdx.app.pause(); //Doesn't exist

            //I don't want to call manually the pause method like this
            //because it doesn't pause Libgdx lifecycle ...
            pause();
        }
    });
    stage.addActor(imagePause);

Any idea?

A: If your goal is to stop the render:
To stop the render:
Gdx.graphics.setContinuousRendering(false);

To put it back on:
Gdx.graphics.setContinuousRendering(true);

To trigger render when the rendering is stop:
Gdx.graphics.requestRendering();

Documentation: https://github.com/libgdx/libgdx/wiki/Continuous-&-non-continuous-rendering
Hope it will help you.


text:
Q: SQL Server Report Builder 3.0 exclude empty fields I am trying to generate reports with SQL Server Report Builder (my first time ever)
And I have a list with this fields: name, order, weight, temp
Sometimes the field order has no value. And I want to filter the rows where order has no value!
With kind regards Marco

A: Are you using a dataset that has a query that you defined? If so you could base your query on the filter input.  So for instance you could add a parameter to your Report Builder Report that passes in a value to your query (All, ,NotMissingOrder).
So the below takes in a param passed in from the report "@FilterParam" which as a value of NotMissingOrder if the filter is selected.  This would exclude those records where Order doesn't have a value from the output.  You could set the default value of the param to = 'All' So that otherwise everything would be returned:
Select *
From Table t
Where(isnull(t.Order,'MissingOrder') = @FilterParam
      Or
      @FilterParam = 'All')


text:
Q: Arabic character print in reverse in EPSON Bluetooth printer TM-P60II I am using EPSON android SDK to print transaction receipt but when trying to print arabic character along with English character, it prints arabic in reverse order.
Like I am printing خدمة تعبئة و تغليف but print
Please let me know the possible solution of this problem.

A: It seems that the current EPSON normal ESC/POS printer/device driver/EPSON's library does not have a right-to-left printing function.
There seems to be an example of taking special measures for a specific version of a specific environment, but it is not something that can be applied to other environments.
Arabic Font Printing via OPOS Printer (EPSON TM-T88V)
Probably, as a countermeasure with the smallest amount of data, create only the Arabic character part as bit image data to be printed with the ESC * command, create the ASCII character part as text, and send them in combination. Will do.

However, TM-P60II does not seem to support the ESC * command.
In that case, you will only be able to use one of the following methods.
GS ( L / GS 8 L
GS D
Programmatically, it would be easy to create all the contents including ASCII and Arabic characters as one bit image data, send it, and print it.
However, the printing speed seems to be slow.
Alternatively, it is possible to determine the presence or absence of Arabic characters on a line-by-line basis, print text data if only ASCII characters are included, and create and print as bit image data if Arabic characters are included.
It's not recommended as the ASCII fonts will be disjointed, but it will be a bit faster than printing everything as a bit image.

For example, is the escpos-php library prototyped with such an issue?
However, it seems that it has not been officially implemented.
Add support for right-to-left text output #6
Arabic printing problem #455
How can i print arabic in POS printer? #757

Alternatively, you could try printing with character encoding by implementing your own inversion of sentences containing Arabic characters, as the Python library module does in this article.
how to fix the reversed Lines when using arabic-reshaper and python-bidi (in multiple lines situation)?


text:
Q: Make a ToolStrip Button staying highlighted when clicked in C# I have a simple ToolStrip with buttons in it which contain images and text. When I go over that button it changes appearance (same when it gets clicked). How can I customize this so that it stays highlighted when clicked? I have to do this over a tabControl so that it stays highlighted when the tab is entered and gets back to its normal appearance when leaving the tab. Which methods do I have to override?
Thank you!

A: just set ToolStripButton.CheckOnClick property to true from design time. So it will stay highlited when clicked.
About the other requirement set ToolStripButton.Checked to true on entring the tab control, and set it to false on leaving the tab control.
For entering and leaving you may use Control.Leave & Control.Enter events of tabpage/tabcontrol.
Let me know incase of any issues


text:
Q: How to put getIntent.getStringExtra("username") in android adapter onBindViewHolder(@NonNull final ViewHolder holder, final int position) i want to call getIntent().getStringExtra() inside this adapter class. I passed username in my previous class. but here I can't call get intent in this adapter class.
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.layout_gig_item, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

    final GigHolder gigHolder = gigList.get(position);

    holder.lbl_title.setText(gigHolder.getTitle());
    holder.lbl_price.setText(Utils.getDecimal(gigHolder.getTotal()));
    holder.lbl_contact.setText(gigHolder.getContact());
    holder.img_cover.setImageURI(gigHolder.getImage());
    holder.ll_main.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(!isAdminView){
                Intent intent = new Intent(activity, GigViewActivity.class);
                intent.putExtra(Constants.BUNDLE_ID, gigHolder.getPrimaryKey());
                activity.startActivity(intent);
            }
        }
    });
}

}

A: It would be better to just get the data from the activity or fragment supporting the adapter class and pass it to the adapter class through a function

A: You have two ways to solve this issue:
First way is to pass the Context of the calling Class as a Constructor parameter of the Adapter. You can then access the StringExtra by calling context.getIntent().getStringExtra().
Second way is to get the StringExtra from your calling Class and then pass it as a Contructor parameter of the Adapter.


text:
Q: Not a GROUP BY expression - OVER(PARTITION BY) I am creating a query where it shows me the total per function per month but I am getting an error - not a GROUP BY expression.
I have this in the select statement -
sum(a.sched_hours) OVER(PARTITION BY d.function) AS total_hours

Anything I can do to show the correct results?

A: Do not use an analytic function, use the normal aggregation function instead:
SELECT function_name,
       TRUNC(dt, 'MM') AS month,
       SUM(sched_hours) AS total_hours
FROM   table_name
GROUP BY
       function_name,
       TRUNC(dt, 'MM')

Which, for the sample data:
CREATE TABLE table_name (function_name, dt, sched_hours) AS
SELECT 'A', DATE '2022-01-01', 10 FROM DUAL UNION ALL
SELECT 'A', DATE '2022-01-02', 10 FROM DUAL UNION ALL
SELECT 'A', DATE '2022-02-01', 20 FROM DUAL UNION ALL
SELECT 'A', DATE '2022-02-02', 20 FROM DUAL UNION ALL
SELECT 'B', DATE '2022-01-01', 20 FROM DUAL UNION ALL
SELECT 'B', DATE '2022-01-02', 20 FROM DUAL UNION ALL
SELECT 'B', DATE '2022-02-01', 30 FROM DUAL UNION ALL
SELECT 'B', DATE '2022-02-02', 30 FROM DUAL;

Outputs:

FUNCTION_NAME
MONTH
TOTAL_HOURS

A
01-JAN-22
20

A
01-FEB-22
40

B
01-JAN-22
40

B
01-FEB-22
60

If you want a grant total for each function across all the months then nest the aggregation function inside the analytic function:
SELECT function_name,
       TRUNC(dt, 'MM') AS month,
       SUM(sched_hours) AS hours,
       SUM(SUM(sched_hours)) OVER (PARTITION BY function_name) AS total_hours
FROM   table_name
GROUP BY
       function_name,
       TRUNC(dt, 'MM')

Which outputs:

FUNCTION_NAME
MONTH
HOURS
TOTAL_HOURS

A
01-JAN-22
20
60

A
01-FEB-22
40
60

B
01-JAN-22
40
100

B
01-FEB-22
60
100

db<>fiddle here


text:
Q: Is there anyway I could set width and layout width to be the same in Directwrite TextLayout? Whenever I render a text using text layout object, it's apparent that actual width of text is not same as the width of layout depending on enable option in text wrapping.
I would like to know if there is anyway I could do to set width and layout width to be the same?
So When I pass in width and height in a creation of text layout object, I want it to render the text in the exact dimension I provided.

A: Initial layout dimensions are used to control word wrapping or trimming, if enabled. So it depends on what you want to achieve, normally you set desired layout box, and text does not have to fit or fully fill to any degree. When rendering you might be interested in effective rectangle that your text fits in fully, you need to call GetMetrics for that, and use returned DWRITE_TEXT_METRICS struct fields. Metrics data will contain actual rectangle sizes for your text, regardless of what you specified on layout creation.


text:
Q: How to cross compile application for 32 bit arm architecture on amd64 system using arm-linux-gnueabihf-g++ in Ubuntu I am new to arm-linuxgnueabihf-g++. I am working on an amd64 machine with Ubuntu 14.04 and having arm-linuxgnueabihf-g++-4.7 installed. I want to cross-compile my application targeting 32-bit arm architecture.
I run command:
arm-linux-gnueabihf-g++ -m32 hello.cpp -o hello.

But it gave me the error: arm-linux-gnueabihf-g++: error:
unrecognized command line option '-m32'.

And seems there is little documentation about arm-linux-gnueabihf-g++ on the Internet.
Can anyone give me some help?

A: -m32 is an x86 option. It is not supported (or needed) on ARM, where different toolchains are used for 32-bit and 64-bit code.
The 64-bit ARM (AArch64) toolchain is called aarch64-linux-gnu.


text:
Q: How to export Editor logs from instruments I am running a test script in the instruments and wanted to export the Editor log messages. Is there any way I can export them into file?

A: I don't know of any way to export the logged messages in the Console to a file from Instruments. You should be able to copy and paste the message text to a text file.


text:
Q: Load PostGIS layer/table to QGIS canvas using Python I want to load a PostGIS layer to QGIS canvas. I am using the following code but it is not loading the layer in canvas.
sql = "(SELECT * FROM table WHERE id = 20)"
uri = QgsDataSourceURI()
uri.setConnection("host", "5432", "databasename", "user", "password")
uri.setDataSource("public","table", "the_geom", sql,"gid")
print uri.uri()
vlayer = QgsVectorLayer(uri.uri(), "test", "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)
canvas.refresh()

But the layer is not loaded. I don't know what I am doing wrong here.

A: The sql-parameter is not what it sounds like. It only takes a where-clause, like 'id = 20' in your case.
So try:
uri.setDataSource("public","table", "the_geom", 'id = 20',"gid")


text:
Q: Display gridview data on click I have a gridview that becomes quite long with some information that could be somewhat hidden.
Here's my asp:
<asp:GridView ID="gvLogBody" runat="server" CssClass="Grid" AllowPaging="true" AllowSorting="true" PageSize="10" AutoGenerateColumns="true">
</asp:GridView>

And here's my code behind:
DataSet ds = new DataSet();
ds.Tables.Add("LogBody");
ds.Tables["LogBody"].Columns.Add("timeStamp");
ds.Tables["LogBody"].Columns.Add("name");
ds.Tables["LogBody"].Columns.Add("message");
foreach (LogObject l in logLines)
{
    ds.Tables["LogBody"].Rows.Add(l.TimeStamp, l.Name, l.Message);
}
gvLogBody.DataSource = ds.Tables["LogBody"].DefaultView;
gvLogBody.DataBind();

This gives me a gridview that looks like this:
____________________________________________________________________________________________
|timeStamp|                      name                     |            message             |
+---------+-----------------------------------------------+--------------------------------+
|01-01-01 | someLongAndQuiteUnnecesaryNameThatIWishToHide | someMessageThatIsMoreImportant |
+---------+-----------------------------------------------+--------------------------------+

What I want is something like this:
_________________________________________________________
|timeStamp|    name     |            message             |
+---------+-------------+--------------------------------+
|01-01-01 | clickToShow | someMessageThatIsMoreImportant |
+---------+-------------+--------------------------------+

And once the user clicks the text, it expands / opens a popup or something.
How can this be done?

A: This piece of code will help you out.
<asp:GridView ID="gvLogBody" runat="server" CssClass="Grid" AllowPaging="true" AllowSorting="true" PageSize="10" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="timeStamp" HeaderText="timeStamp" />
                        <asp:TemplateField HeaderText="name">
                            <ItemTemplate>
                                <input type="button" value="clickToShow" onclick="alert('<%#Eval("name") %>')" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="message" HeaderText="message" />
                    </Columns>
                </asp:GridView>

A: Why not use jQueryUI Dialog for good look and feel of popup

     <link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

then in body
<asp:GridView ID="gvLogBody" runat="server" CssClass="Grid" AllowPaging="true" AllowSorting="true" PageSize="10" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="timeStamp" HeaderText="timeStamp" />
                        <asp:TemplateField HeaderText="name">
                            <ItemTemplate>
                                <a href="#" onclick='javascript:return openPopup("<%#Eval("name") %>");'>
                                <%#Eval("name")%>

                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="message" HeaderText="message" />
                    </Columns>
                </asp:GridView>

        <asp:Label ID="lblName" runat="server" ></asp:Label>


text:
Q: MVC dropdown / HTML Select selected item to model Trying to use HTML.Select in place of dropdown.for because for some reason the model is reporting as bring null. (That is not the main issue but I would like to know the reason for that) The issue concerning me is that because I am using a standard html select control, the view cannot associate the selected item value to a model property.
View is as follows:
@model CustomerPortal.ViewModels.Interfaces.ICustomerEmailViewModel

@{
 ViewBag.Title = "Create";
 Layout = "~/Views/Shared/_Layout.cshtml";
}

Create

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

CustomerEmailViewModel

    @Html.ValidationSummary(true, "", new {@class = "text-danger"})

            @Html.LabelFor(model => model.CustomerId, new {@class = "control-label col-md-2"})

            <select id="Customer_Id" name=" Customer" onchange="this.options[this.selectedIndex].value;"></select>
            @Html.HiddenFor(model => model.CustomerId, new {id = "hdnCustomerId"})

            @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new {@class = "control-label col-md-2"})

                @Html.EditorFor(model => model.EmailAddress, new {htmlAttributes = new {@class = "form-control"}})
                @Html.ValidationMessageFor(model => model.EmailAddress, "", new {@class = "text-danger"})

    @Html.ActionLink("Back to List", "Index")

The controller:
[ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(CustomerEmailViewModel customerEmail)
    {

        if (ModelState.IsValid)
        {
            CustomerEmail cevm = new CustomerEmail
            {
                Id = customerEmail.Id,
                EmailAddress = customerEmail.EmailAddress,
                CustomerId = customerEmail.CustomerId,
                CustomerEmailTypeId = customerEmail.CustomerEmailType.Id
            };

            try
            {
                _portalUow.CustomerEmailRepository.Insert(cevm);
                _portalUow.Save();
            }
            catch (Exception)
            {
                Danger("An exception occured while updating the database.  The transaction was rolled back");
                return null; // System.Web.UI.WebControls.View(customer);
            }

            return RedirectToAction("Index");
        }

        return View(customerEmail);
    }

Thank you for any help with this....

A: Try to use @Html.DropDownListFor
@Html.DropDownListFor(model => model.property, new SelectList(Model.dropdownlist, "Value", "Text"), new { @class = "form-control" })

In controller you will need to assign the value of dropdownlist to Model.dropdownlist too. For example:
var list = new SelectList(new[]
        {
            new {ID="CustomerId1", Name="CustomerId1" },
            new {ID="CustomerId2", Name="CustomerId2" },
        }, "ID", "Name", 1
        );
        your list instance = list;


text:
Q: Need an Asp.net MVC Application solution I have implemented a small ordering and stock control system (for internal using) with the MVC 2 framework. Now my friends, they want to have a website to present the existing products for their customers. I know, I know they will ask me to do this one day. So in the beginning, I have made the controller name to start with "Admin". But now I am not sure the best way to implement their requirements. Could you advise me?
1.For the security reason, I did not allowed anonymous user to access the website a part from the CSS and image files. My question is the controllers' name are not folders' name, how could I set this up?
<!--Only allow the anonymous users to access the content folder-->
<location path="Content">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>

2.I'm planning to put the admin section into an "area" and will it be a good way to go? Can anyone provide me some suggestions.
Many thanks.

A: *

*If the built-in Authorize filter doesn't work for you, you can always implement a custom authorization filter.

*If you have a large project (hundreds of views), then yes, I do think using areas is a good idea.

A: MVC use routing to serve the requests.
There is no folder to control access rights. Instead you can use Attributes on top of controllers, or on top of action methods.
I see you have a base controller, you could decorate your base controller with the appropriate Authorize attribute...
I don't agree with Buu about Areas. I think that areas to separate the section of a website makes the project structure easier to understand. It will also let you place the routing configuration inside their area instead of having everything in your global.asax.
I think it's worth it even before you have a lot of views. Admin/Public is a classic case.
follow the link from Buu..

A: Personally, I'd create a completely different website to handle public access.  Best way to secure a view is to not have it in the first place.
Second option would be to create two areas, Internal and Public.  You can secure each by dropping a web.config within each area folder, the one in Public allowing for anonymous access and the one in Internal restricting access to people logged into your office domain.
Third option is to perform security culling in your controller methods.  This would require lots of work and would be a good idea to do this anyhow, but realize a bug here means you have a vulnerability in your system.


text:
Q: Running out of memory when using a Hashmap for storing a psuedo infinite game world in Android Continuing from a previous question regarding infinite game worlds and coordinate data structures I have decided to go with a Hashmap. However, since I am trying this on Android I quickly ran into problems.
Here is a recap of requirements:

*

*Psuedo-infinite 2D world of tiles. The world will be generated as
explored in all 4 directions (2D) So we need something that goes to
negative indexes.

*Random access will be required for adjacent tiles
etc.

*Need to be able to retrieve tile from a specific coordinate like
get(x,y)

So, here is a snip of code I used to create a hashmap of 600 * 600 tiles.
Class for each Map tile:
public class MapTile {
    public int type;

    public MapTile(int type) {
        this.type = type;
    }

    public boolean is(int type) {
        return (type==this.type);
    }
}

Test code for generating a big map:
long startTime;
long lastTime;
map = new HashMap<Point, MapTile>();
int x;
int y;
int tile;
startTime = System.currentTimeMillis();
lastTime = startTime;
for (x=-300;x<=300;x++) {
    for (y=-300;y<=300;y++) {
        tile = (x+y)%2; //Just so I differentiate the tiles
        this.map.put(new Point(x,y), new MapTile(tile));

    }
    // Logging each row
    Log.d(this.getClass().toString(), "Generated x:" + x + " Time in ms:"+(System.currentTimeMillis() - lastTime));
    lastTime = System.currentTimeMillis();

}

So, when I run similar code in Java. It completes successfully (eats a lot of memory though). No problem.
But, when I try to do this in Android on a top-end device, it practically halts before reaching x = 190 mark (usually). Garbage collector kicks in, and endless loop ensues:
** snip **
05-26 15:52:19.565  10758-10758/com.ayk.test04        D/class com.ayk.test04.WorldMap2D: Generated x:187 Time in ms:2
05-26 15:52:19.570  10758-10758/com.ayk.test04        D/class com.ayk.test04.WorldMap2D: Generated x:188 Time in ms:6
05-26 15:52:19.575  10758-10758/com.ayk.test04        D/class com.ayk.test04.WorldMap2D: Generated x:189 Time in ms:2
05-26 15:52:19.995  10758-10760/com.ayk.test04        I/dalvikvm-heap: Clamp target GC heap from 66.002MB to 64.000MB
05-26 15:52:19.995  10758-10760/com.ayk.test04        D/dalvikvm: GC_CONCURRENT freed 3K, 2% free 64797K/65543K, paused 4ms+30ms, total 429ms
05-26 15:52:19.995  10758-10758/com.ayk.test04        D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 421ms
05-26 15:52:20.335  10758-10758/com.ayk.test04        I/dalvikvm-heap: Clamp target GC heap from 66.002MB to 64.000MB
05-26 15:52:20.335  10758-10758/com.ayk.test04        D/dalvikvm: GC_FOR_ALLOC freed 0K, 2% free 64797K/65543K, paused 341ms, total 341ms
05-26 15:52:20.335  10758-10758/com.ayk.test04        I/dalvikvm-heap: Clamp target GC heap from 64.002MB to 64.000MB
05-26 15:52:20.335  10758-10758/com.ayk.test04        I/dalvikvm-heap: Grow heap (frag case) to 64.000MB for 16-byte allocation
05-26 15:52:20.695  10758-10760/com.ayk.test04        I/dalvikvm-heap: Clamp target GC heap from 66.002MB to 64.000MB
05-26 15:52:20.695  10758-10760/com.ayk.test04        D/dalvikvm: GC_CONCURRENT freed 0K, 2% free 64797K/65543K, paused 12ms+2ms, total 358ms
05-26 15:52:20.695  10758-10758/com.ayk.test04        D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 332ms
** thousands of these... snip **

So, pretty much, I am stuck here.
My tiles only contain an int variable for now. This is barebones. So I understand, it is technically impossible to create a Hashmap of 50.000 or so objects? This seems a bit small for me.
Things I want to try are:

*

*Only keeping a live region of the map in memory while offloading the rest to storage. While this may solve the memory issue, I am afraid it may cause performance problems while accessing tiles that are out of the live area.

*Somebody suggested using chunks (ala Minecraft). So I keep a hashmap of hashmaps? Would it work? If so, how do I do it?

*Am I completely off the target and looking at this the wrong way?

Thanks for any help you may bring in.
Update
Hello again. With your help, I have decided to go with using a database. It works much more efficiently and so far, I haven't run into any problems. For posterity, here is how it works:
The database
Working in Android, I have set up an SQLite database and table for storing each tile. At first, I decided to run an insert query each time a tile is generated. This quickly turned out to be another performance bottleneck because each INSERT took a bit over 2ms to complete, throwing a wrench into even the smallest 300x300 tile generation process. I had to utilize a multiple INSERT query which took many tiles and stored them using a single query. So, I have created an "tile buffer" where each tile is stored with their coordinates:
//A linked list of integers is good enough.
//The first 2 are X and Y coordinates, the third one is the tile type.
//I can add more fields if needed.
this.tileDBbuffer = new LinkedList<Integer[]>();

Here is how the buffer is filled:
void addTileBuffer(int x,int y, MapTile map_tile) {
    int maxsize = 10000;
    Integer[] tile_data;
    tile_data = new Integer[3];
    tile_data[0] = x;
    tile_data[1] = y;
    tile_data[2] = map_tile.type;
    if (this.tileDBbuffer.size()>= maxsize) {
        Log.d(this.getClass().toString(), "Buffer filled up... Saving");
        savemapbuffer();
    }
    this.tileDBbuffer.add(tile_data);
}

Once the buffer reaches a certain size (or the tile generation ends) the "savemapbuffer()" function is ran, which basically calls this function first, and then purges the buffer:
public void addTileBulk(LinkedList<Integer[]> map_tiles) {
    Integer[] tile_data = new Integer[3];

    if (db == null) db = this.getWritableDatabase();

    String sql = "INSERT INTO "+TABLE_NAME_MAP+" ("+COLUMN_NAME_MAP_X+", "+COLUMN_NAME_MAP_Y+", "+COLUMN_NAME_MAP_TILE_TYPE+") VALUES (?,?,?)";
    db.beginTransaction();
    SQLiteStatement stmt = db.compileStatement(sql);
    try {
        while (!map_tiles.isEmpty()) {
            tile_data = map_tiles.pop();
            stmt.bindLong(1,tile_data[0]);
            stmt.bindLong(2,tile_data[1]);
            stmt.bindLong(3,tile_data[2]);
            stmt.execute();
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();

    }

    map_tiles.clear();
}

Hashmap in use
Soon after this, problems occurred while drawing the map. The drawing is done in another thread, so iterating through it while simultaneously generating new tiles threw lots of weird errors. After testing for a bit using "is the map busy" booleans, I ended up using a ConcurrentHashmap instead of a regular Hashmap. It worked.
Chunks
After that, I ended up needing to use "chunks" after all. It was easier to manage discrete sections of the map rather than estimating which tiles to load based on player distance. So now, each HashMap element is a fixed 2 dimensional integer array, containing tiles. I call them Cells
map = new ConcurrentHashMap<Point, MapCell>();

and a cell is something like this:
public class MapCell {
    public int x,y;
    private static int cell_size = 32;
    public MapTile[][] tiles = new MapTile[cell_size][cell_size];
}

Now. I am off to Perlin noise and map generation adventures :) See you next time.

A: You might have to go with your first option of keeping a subset in memory, especially if your game world grows much larger. To minimize the performance hit, you can consider something like creating 30x30 subtiles. At any point of time, keep the current subtile loaded while loading the 8 adjacent 30x30 subtiles in the background. When the player character transitions between subtiles it will load fast as it is already loaded, then while he is exploring the new subtile you can load the next one into memory, etc..
If you follow the subtiles strategy (with the subtile boundaries aligned to multiples of 30) you don't have to constantly check, but only when you cross a subtile boundary. Also by loading 30x30 at once you can minimize database or file access. You also don't need to use a HashMap: represent each subtile as a 30x30 array, and store the top left coordinate of the current center subtile. You should then be able to do some math to retrieve the relevant tile in the 90x90 vicinity if needed.


text:
Q: How to configure a management IP address on a router on a stick? I'm setting up a simple Router on a stick following this tutorial (https://www.youtube.com/watch?v=2_xpsk-uRug&t=338s) The actual routing part works fine, however, I'm struggling to assign the router a management IP address.
The current router (Cisco 1841) configuration is:
 - interface FastEthernet0/0
 no ip address
 duplex auto
 speed auto
!

 - interface FastEthernet0/0.100
 encapsulation dot1Q 100
 ip address 10.0.100.1 255.255.255.0
!

 - interface FastEthernet0/0.150
 encapsulation dot1Q 150
 ip address 10.0.150.1 255.255.255.0
!

 - interface FastEthernet0/0.200
 encapsulation dot1Q 200
 ip address 10.0.200.1 255.255.255.0
!
 - interface FastEthernet0/0.201
 encapsulation dot1Q 201
 ip address 10.0.201.1 255.255.255.0
!

 - interface FastEthernet0/1
 no ip address
 shutdown
 duplex auto
 speed auto
!

I've tried SSHing to 10.0.100.1 - no luck
I've tried:
interface fa0/0
ip address 10.0.100.11 255.255.255.0

returns an error:

IP overlaps with FA0/0.100.

Also tried using:
VLAN 100
IP address 10.0.100.11 255.255.255.0

This just isn't a valid command.
kind regards


text:
Q: Section names from NSFetchedResultsController don't match the managed object values I'm using an NSFetchedResultsController to populate a UITableView with results from a moderately sized Core Data store of ~1500 entities. The results controller is fairly standard - some "hot spots" for potential bugs aren't true of this setup.

*

*Managed object context created on the same (main) thread as its used on

*No cache is used (because the sort changes frequently)

*A sectionNameKeyPath is used to split the results into sections

My section results, however, are very odd. For example, consider this method used to set the titles for the section header views:
- (NSString *)titleForHeaderInSection:(NSInteger)section {
  id <NSFetchedResultsSectionInfo> sectionInfo = [[self.resultsController sections] objectAtIndex:section];
  return [sectionInfo name];    // <------- Stopped at breakpoint here
}

I've stopped at the indicated line using a breakpoint and, using GDB, examined the following:
(gdb) po [[self resultsController] sectionNameKeyPath]
reviewDateString
(gdb) print section
$11 = 1
(gdb) print (int) [sectionInfo numberOfObjects]
$12 = 4
(gdb)  po [sectionInfo name]
Wednesday, September 8th 2010
(gdb) po [[[sectionInfo objects] objectAtIndex:0] valueForKey:@"reviewDateString"]
Sunday, February 13th 2011
(gdb) po [[[sectionInfo objects] objectAtIndex:1] valueForKey:@"reviewDateString"]
Sunday, February 13th 2011
(gdb) po [[[sectionInfo objects] objectAtIndex:2] valueForKey:@"reviewDateString"]
Sunday, February 13th 2011
(gdb) po [[[sectionInfo objects] objectAtIndex:3] valueForKey:@"reviewDateString"]
Sunday, February 13th 2011

The issue should be evident - why doesn't [sectionInfo name] match the values of the sectionNameKeyPath for each managed object in the section? The objects in the section appear to be properly grouped, the section name just isn't correctly set.
The results are even more odd if you look at this:
(gdb) po [[self resultsController] indexPathForObject:(id)[[sectionInfo objects] objectAtIndex:0]]
<NSIndexPath 0x6615660> 2 indexes [459, 4294966310]

Now obviously, from the above, the NSIndexPath returned should be [1,0], not this bogus value.
I'm completely stumped. Anyone have any ideas? I'll be watching this question in case you need more information.
[Edit 1]
The one odd thing about my NSFetchedResultsController setup is that I recreate (release and alloc/init a new one) the results controller in response to a UISegmentedControl's selection changing. This is done in order to change the sortDescriptors of the fetch request and sectionNameKeyPath, so that the overall sort changes.
[Edit 2]
The resultsController method is just the property accessor for the NSFetchedResultsController that I'm using, generated by @synthesize.
The expected values for the section names are given already - the section names should be equal to the values for the @"reviewDateString" key (which is the sectionNameKeyPath) that I showed just below "po [sectionInfo name]", so for this case they should be "Sunday, February 13th 2011".

A: You likely need to fix your sectionNameKey on the fetch.

If this key path is not the same as that specified by the first sort descriptor in fetchRequest, they must generate the same relative orderings. For example, the first sort descriptor in fetchRequest might specify the key for a persistent property; sectionNameKeyPath might specify a key for a transient property derived from the persistent property.


text:
Q: Determine password used for ZIP file I have a password-protected ZIP file that contains a single file. Also I have the same file outside the archive in a plain version. I know for sure that this is the same file. Is it possible to determine the password used for this archive?
To be clear, I want to know the actual password used for the ZIP file; I'm not trying to simply gain access to the ZIP file's content without knowing the password.
My question is not answered by this proposed duplicate question. That question deals with accessing the ZIP file without knowing the password. I am trying to compute the password leveraging the fact I have the same file inside and outside the archive.

A: Your answer is "it depends" and "probably not".  Apparently ZIP files support different types of encryption, and the ability to reverse engineer the password would be dependent on the type of encryption.
Probably the most popular encryption will be a variant of AES encryption, and it is generally accepted as being unbreakable in reality - and indeed, most suitable decent encryption methods will share this attribute.

A: There is program called pkcrack which could be useful here. But after searching for a password with it, nothing has been found. It taken half an hour and no result.


text:
Q: Using Flux.cache to reuse Redis channel subscription in webflux I am using Spring webflux to build an endpoint that will stream events received from a Redis channel subscription.
It's something like this:
class MyService(redisTemplate: ReactiveRedisOperations<String, String>) {

    private val redisChannelFlux = redisTemplate
            .listenToChannel("myChannel")
            .map { it.message }
            .cache(0) // transforms this FLux into a reusable Hot publisher

    fun watch() : Flux<String> {
        return redisChannelFlux
    }

}

class MyController(val svc: MyService) {

    @GetMapping("/api/watch", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun watch() : Flux<String> {
        return svc.watch()
    }

}

It works. When a client subscribes to the /api/watch endpoint it starts receiving new events from the Redis channel, and I can confirm in the Redis monitor that "SUBSCRIBE" "myChannel" happens only once, regardless of how many clients are connected to my reactive endpoint. Awesome!
I am just not sure how safe it is to use Flux.cache() in this scenario. Am I flirting with disaster here? Is there a recommended way of reusing an existing Publisher with new Subscribers?

A: Flux.cache() is usually used for replaying to new subscribers the last N elements of that Flux. Since here you're setting that number to 0, it seems you're just interesting in sharing resources, and not replaying the latest events to a new subscriber.
With that in mind, you can just use Flux.share() instead. This operator will subscribe to your redis instance as soon as a first subscriber comes in, and share the resources with all others. Once all subscribers are gone, the connection to your redis instance is closed, until another subscriber comes, etc.


text:
Q: Trimming MySQL string after a given string I'm drawing a blank on this MySQL command. I have a set of strings like so in a variable named pagetitle in a table called scanner:
Marketing analytics via Christopher Penn

And I want to lop off everything after, including the via, to yield:
Marketing analytics

I did this:
UPDATE scanner SET pagetitle = SELECT TRIM(TRAILING ' via ' FROM pagetitle) FROM scanner

Which according to the manual should do what I'm looking for, but it's still yielding the original string.
What am I doing wrong?

A: The TRAILING option with TRIM refers to trailing characters, not entire words begun with a certain word.  Try using INSTR here:
UPDATE scanner
SET pagetitle = LEFT(pagetitle, INSTR(pagetitle, 'via') - 2);
WHERE pagetitle REGEXP '[[:<:]]via[[:>:]]';

Demo
If you are using MySQL 8+ or later, then we can try using REGEXP_REPLACE:
UPDATE scanner
SET pagetitle = REGEXP_REPLACE(pagetitle, '\\s+via.*', '');