text:
Q: Writing a vector of vector vector structure to a binary file std::vector<std::vector<std::vector<sphere_data> >> Sphere_image ;

I want to write the data in sphere image to binary file.
Could any one tell me how can this be done.
I tried this Code:
ofstream fout("C:/Project/data.dat", ios::out | ios::binary);
fout.write((char*)&Sphere_image[o], Sphere_image.size() *
sizeof(sphere_data));
fout.close();

A: A multi-dimensional vector is not stored in consecutive memory locations, like a multi-dimensional array is.
Your vector contains a
 std::vector<std::vector<sphere_data>>

This is just an array of vector structures themselves. Sphere_image.size() gives you the number of values in the top level dimension of the multi-dimensional vector, that's all.
First of all, this will only work if sphere_data is a POD. If it is a class, this will not work. You have to iterate over each dimension separately:
ofstream fout("C:/Project/data.dat", ios::out | ios::binary);

for (const auto &dim: Sphere_image)
   for (const auto &dim2:dim)
      fout.write(&dim2[0], dim2.size() * sizeof(sphere_data));

fout.close();

A: When you have nested std::vectors, you don't have contiguity in memory for the whole data structure.
So, you have to iterate through all the nested vectors "dimensions", and assume contiguity of sphere_data instances only in the innermost vector.
So, your line:

fout.write((char*)&Sphere_image[o], Sphere_image.size() *
sizeof(sphere_data));

must be expanded something like that:
for (const auto& vi : Sphere_image) { // For each outer vector
  for (const auto& vj : vi) {         // For each sub-vector
    // Now you do have contiguity for vj
    fout.write(
        reinterpret_cast<const char*>(vj.data()),
        vj.size() * sizeof(sphere_data));
  }
}

Note that this assumes that sphere_data is a POD, so e.g. if you have pointer data members inside sphere_data, that won't work.
In this case, you may provide a sphere_data::save(std::ofstream& out) const method, which you can call in the innermost loop. Instances of sphere_data will know how to serialize themselves to binary files. E.g.:
for (const auto& vi : Sphere_image) { // For each outer vector
  for (const auto& vj : vi) {         // For each sub-vector
    for (const auto& sd : vj) {       // For each sphere data
      sd.save(fout);
    }
  }
}

You may also provide a symmetrical sphere_data::load() method as well.


text:
Q: Why android layout_weight does not work as expected? I have two linearlayouts, each occupy the 50% of total space.
Inside of them there are different views and I don't understand why the horizontalScrollView1 and the listView1 (look the ids) are not visible.
The two views should expand to fill the space remaining in their parent.
What I'am doing wrong?
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
       android:layout_height="0dp"
       android:layout_weight="1"
       android:layout_width="match_parent">
       <HorizontalScrollView
         android:id="@+id/header"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"/>
       <HorizontalScrollView
         android:layout_height="0dp"
         android:layout_weight="1"
         android:layout_width="match_parent"
         android:id="@+id/horizontalScrollView1">
         <ListView
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:id="@+id/list"/>
       </HorizontalScrollView>
    </LinearLayout>
    <LinearLayout
      android:layout_height="0dp"
      android:layout_weight="1"
      android:layout_width="match_parent"  >
      <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Hello!!!" />
      <ListView
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_weight="1"
         android:id="@+id/listView1"/>
    </LinearLayout>
 </LinearLayout>

A: You forgot to set android:orientation="vertical" to both LinearLayout of main LinearLayout. This way the child of LinearLayout are placed in vertical direction and will be visible.

A: You are using match_parent to your elements, so when one of them takes the full width the other one haven't got a place to draw. Set your inner elements width to wrap_content. And the orientations to the LinearLayout if you don't do it weight doesn't work.
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
       android:layout_height="0dp"
       android:layout_weight="1"
       android:layout_width="match_parent"
       android:orientation="vertical">
       <HorizontalScrollView
         android:id="@+id/header"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
       <HorizontalScrollView
         android:layout_height="0dp"
         android:layout_weight="1"
         android:layout_width="wrap_content"
         android:id="@+id/horizontalScrollView1">
         <ListView
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:id="@+id/list"/>
       </HorizontalScrollView>
    </LinearLayout>
    <LinearLayout
      android:layout_height="0dp"
      android:layout_weight="1"
      android:layout_width="match_parent"
      android:orientation="vertical">
      <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Hello!!!" />
      <ListView
         android:layout_width="wrap_content"
         android:layout_height="0dp"
         android:layout_weight="1"
         android:id="@+id/listView1"/>
    </LinearLayout>
 </LinearLayout>

A: Check this out , I have coloured the required blocks also to differentiate.
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:background="@color/accent"
            android:layout_width="match_parent">
            <HorizontalScrollView
                android:id="@+id/header"
                android:background="@color/primary"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <HorizontalScrollView
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:background="@color/black"
                android:id="@+id/horizontalScrollView1">
                <ListView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/list"/>
            </HorizontalScrollView>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:background="@color/green"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_width="match_parent"  >
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Hello!!!" />
            <ListView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:id="@+id/listView1"/>
        </LinearLayout>
    </LinearLayout>

Basically you have forgotten to add orientation=vertical at some places , plus need to specify android:layout_weight="1" for your both HorizontalScrollView.

A: This is happening because you didn't mention weight for @+id/header horizontal scroll view. So it is taking full height of it's parent linear layout. And you forgot to add orientation type for both parent linear layouts.
You can check by this xml layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <HorizontalScrollView
            android:id="@+id/header"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <HorizontalScrollView
            android:id="@+id/horizontalScrollView1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">

            <ListView
                android:id="@+id/list"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </HorizontalScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello!!!" />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rings of Saturn - initial conditions I'm working on a simulation of the Saturn system that will allow the user to, for example, increase the mass of its largest Moon Titan to that of Earth and see how the other moons and rings get perturbed as a result. My representation of the rings is a crude particle system where each particle starts out with a set of x, y, z position and velocity vectors. If I set the z position and velocity vectors to 0, I get a fairly nice looking ring that rotates around Saturn, but the problem is that Saturn has an axial tilt (the inclination of its axis of rotation to its orbital plane) of 27 degrees, so you have to take the z position and velocity vectors into account for the simulation to be at least somewhat realistic, but after lots of moaning and groaning, I haven't been able to get the inclination of the rings right.
This is the method that creates the initial conditions for the particles that make up the ring:
init() {

  for (let i = 0; i < this.numberOfParticles; i++) {

    const rad = Math.PI * 2 * Math.random();
    const dist = (25 + 20 * Math.random()) / 32000;

    this.particles.push({
      x: Math.cos(rad) * dist,
      y: Math.sin(rad) * dist,
      z: 0,
      vx: (Math.cos(rad + Math.PI / 2 + (Math.PI / 180 * 6 - Math.PI / 180 * 12) * 0) * Math.sqrt(500 / dist)) / 120,
      vy: (Math.sin(rad + Math.PI / 2 + (Math.PI / 180 * 6 - Math.PI / 180 * 12) * 0) * Math.sqrt(500 / dist)) / 120,
      vz: 0
    });

  }

}

Is there anybody out there that could help me figure out how to get the z position and velocity vectors right given the code above? As mentioned above, the axial tilt should be 27 degrees.

A: Just a concept of how you can do it:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 20);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setClearColor(0x101010);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var sun = new THREE.Mesh(new THREE.SphereGeometry(2, 16, 8), new THREE.MeshBasicMaterial({
  color: "orange"
}));
scene.add(sun);

var orbitGeom = new THREE.CircleGeometry(10, 32);
orbitGeom.rotateX(-Math.PI * 0.5);
orbitGeom.vertices.shift();
var orbit = new THREE.LineLoop(orbitGeom, new THREE.LineBasicMaterial({
  color: "yellow"
}));
scene.add(orbit);

var saturnSys = new THREE.Group();
var saturnSysAxis = new THREE.Vector3(0, 1, 0);
saturnSys.rotation.z = THREE.Math.degToRad(27);
saturnSys.add(new THREE.AxesHelper(5));
var saturnPlanet = new THREE.Mesh(new THREE.SphereGeometry(1, 8, 6), new THREE.MeshBasicMaterial({
  color: 0xFACE8D,
  wireframe: true
}));
saturnSys.add(saturnPlanet);

var saturnRingGeom = new THREE.Geometry();
var vertices = [];
for (let i = 0; i < 2000; i++) {
  let r = THREE.Math.randFloat(1.5, 4);
  let angle = THREE.Math.randFloat(0, Math.PI * 2);
  let v = new THREE.Vector3(
    Math.cos(angle) * r,
    0,
    Math.sin(angle) * r
  );
  v.angularVelocity = THREE.Math.randFloat(0.1, Math.PI);
  vertices.push(v);
}

saturnRingGeom.vertices = vertices;

var saturnRing = new THREE.Points(saturnRingGeom, new THREE.PointsMaterial({
  size: 0.1,
  color: "red"
}));
saturnSys.add(saturnRing);

scene.add(saturnSys);

var clock = new THREE.Clock();
var time = 0;
var delta = 0;

render();

function render() {
  requestAnimationFrame(render);
  delta = clock.getDelta();
  time += delta * 0.1;
  saturnSys.position.set(
    Math.cos(time) * 10,
    0,
    Math.sin(time) * 10
  );
  saturnPlanet.rotation.y = time * 3;
  saturnRing.geometry.vertices.forEach(v => {
    v.applyAxisAngle(saturnSysAxis, v.angularVelocity * delta);
  });
  saturnRing.geometry.verticesNeedUpdate = true;
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.min.js"></script>


text:
Q: Why xtratabpage width is 0? I'm using xtratabcontrol from devexpress,,
I need to get the width of the header .
So I write (getting first header width)
int width = browserTabControl.TabPages[0].TabPageWidth;

it gets zero !! although here's the tabpage :

why is this occuring ?
any other ideas to
get the header width are welcomed
thanx in advance

A: try instaed of
int width = browserTabControl.TabPages[0].TabPageWidth;

this code :
int width = browserTabControl.TabPages[0].Width;

A: If the XtraTabPage.TabPageWidth property is set to 0, the header width of the current page is determined by the XtraTabControl.TabPageWidth property. And if the XtraTabControl.TabPageWidth property is set to 0, the headers will be auto-sized to fit the header text.


text:
Q: MATLAB - recompiled executable smaller than original I'm re-compiling code written by a colleague approx 2 years ago. The executable he previously compiled  from this code is 1900kb in size. When I compile it it's only 600kb. I would assume this difference in size means I'm missing files from the build, but all the functionality is there and the executable seems to work fine. My question is: has anyone experienced this before? And does anyone have an explanation as to why the size would change this much?
My colleague and I used different machines but the same OS (windows) and the same version of MATLAB (2012b 32bit).


text:
Q: How to find the value for a key in unordered map? I am trying to do the below sample in unordered map in c++
my_dict = {'one': ['alpha','gamma'], 'two': ['beta'], 'three' : ['charlie']}
print(my_dict["one"]) // ['alpha','gamma']

I tried using find operator like below
int main ()
{
std::unordered_map<std::string, std::vector<std::string>> dict;
dict["one"].push_back("alpha");
dict["one"].push_back("beta");
dict["two"].push_back("gamma");
 auto it = dict.find("one");
 cout<<it->second<<endl; // expected output alphabeta
return 0;
}

But I am not able to retrieve the value for this key dict["one"]. Am i missing anything ?
Any help is highly appreciated.
Thanks

A: This is because your it->first will point to the key of the dictionary i.e. "One" and it->second will point to the value i.e. the vector.
So to print elements of the vector you need to specify the indexes of the vector that you are printing as well. The following code will give you the result you want:
int main() {
std::unordered_map <std::string, std::vector<std::string>> dict;
dict["one"].push_back("alpha");
dict["one"].push_back("beta");
dict["two"].push_back("gamma");
auto it = dict.find("one");
cout<<it->second[0]<<it->second[1]<<endl; // expected output alphabeta
return 0;

}
P.S. Please accept my answer if you find it useful as that would help me get some reputation points

A: The failure you are encountering is due to it->second being a std::vector object, which cannot be printed to std::cout because it lacks an overload for operator<<(std::ostream&,...).
Unlike languages like Python that do this for you, in C++ you must manually loop through the elements and print each entry.
To fix this, you will need to change this line:
 cout<<it->second<<endl; // expected output alphabeta

To instead print each object in the container. This could be something simple like looping through all elements and printing them:
for (const auto& v : it->second) {
    std::cout << v << ' '; // Note: this will leave an extra space at the end
}
std::cout << std::endl;

Or you can go more complex if the exact formatting is important.

@DanielLangr posted a link in the comments to the question that summarizes all possible ways of doing this, and I recommend taking a look if you're wanting anything more complex: How do I print the contents to a Vector?


text:
Q: GroovyMock not working when used to test Java class with static method call Groovy test does not create a mock for static class, when that class is used inside other Java class. Below is a code snippet that proves this
Java class under test:
public class JavaClass {
    public void method() {
      ClassWithStaticMethod.doSomething();
    }
}

Java class with static method:
public class ClassWithStaticMethod {
    public static void doSomething() {
        System.out.println("Static method called");
    }
}

Groovy test that fails:
class JavaClassTest extends Specification {
  def 'test'() {
    given:
    GroovyMock(ClassWithStaticMethod, global: true)
    JavaClass javaClass = new JavaClass()

    when:
    javaClass.method()

    then:
    1 * ClassWithStaticMethod.doSomething() // <--- FAILS
  }
}

This fails with message:
Static method called <--- original method is called, it's not mocked

Too few invocations for:

1 * ClassWithStaticMethod.doSomething()   (0 invocations)

Unmatched invocations (ordered by similarity):

None

So, static method is not mocked and the actual implementation is always called. Can anyone explain this behaviour? Any idea how to bypass this?
Java version: 1.7.0_79, Groovy version: 2.4.7, Spock version: 1.0-groovy-2.4, cgclib: 3.1

A: If java codes are compiled with groovyc
    def "foo"() {
      setup:
        // GroovyMock(ClassWithStaticMethod, global: true)
        GroovySpy(ClassWithStaticMethod, global: true)
        JavaClass javaClass = new JavaClass()

      when:
        javaClass.method()

      then:
        // 1 * ClassWithStaticMethod.doSomething()
        1 * ClassWithStaticMethod.doSomething() >> null
    }

If java codes are compied with javac
1.prepare test code(this sample is MySpock.groovy)
// This Grabs are used for compile.
// These libraries must specifiy on class path when the file executs.
@Grapes([
  @Grab(group='org.jmockit', module='jmockit', version='1.8'),
  @Grab(group='org.spockframework', module='spock-core', version='1.0-groovy-2.4')
])

import spock.lang.*
import mockit.*

class MySpock extends Specification {

  def "hoge"() {
    setup:

    // Overwrite ClassWithStaticMethod#doSomething(static method) with JMockit/MockUp
    new MockUp<ClassWithStaticMethod>() {
      @Mock
      public static void doSomething() {
        Logger.append("abc")
      }

    }

    // Target object for this test
    JavaClass javaClass = new JavaClass()

    when: "Execute target method"
    javaClass.method()

    then: "ClassWithStaticMethod#doSomething was mocked and write the value in a file"
    Logger.count() == 1

    cleanup: "Delete log file for this test"
    Logger.delete()
  }
}

// Logging Utility for only this test.
class Logger {
  static logFile = new File("/tmp/MySpock.groovy.log")
  static append = {String msg -> logFile.append("${msg}${System.getProperty("line.separator")}")}
  static count = {logFile.readLines()?.size()?:0}
  static delete = { logFile.delete() }
}

2.compile codes
javac ClassWithStaticMethod.java&&javac JavaClass.java&&groovyc MySpock.groovy

3.execute test
groovy -cp .:$HOME/.groovy/grapes/org.jmockit/jmockit/jars/jmockit-1.8.jar:$HOME/.groovy/grapes/org.spockframework/spock-core/jars/spock-core-1.0-groovy-2.4.jar MySpock

I have used JMockit at first time.
So, I don't know whether this usage is correct.
I have no idea for method that access and add staic field each other between Spock and Mock(JMockit).
Therefore i created log file to check whether the "ClassWithStaticMethod#doSomething" is called from the "JavaClass#method".


text:
Q: Lossless TIFF or PNG export I'd like to export an output from MatrixPlot[], however, the output file size seems to depend on my specification of the ImageSize -> {..., ...}.  How might I export a TIFF with all of the data in the $N \times M$ matrix being plotted?  Presumably one could set the ImageSize to reflect the matrix dimensions, however, how would one appropriately pad for the axes and axes labels?
The command I'm using for MatrixPlot[] export is:
Export["MatrixExportFileExample.tiff",MatrixPlot[...]];

A: I think what you are looking for is the PixelConstrained option of ArrayPlot, or understanding of its mechanism using Raster and Offset.  With the default settings you will need Frame -> False to show all values (the frame overlaps the outer pixels).
data = CellularAutomaton[{1635, {3, 1}}, {{1}, 0}, 80];

ArrayPlot[data,
 ColorRules -> {0 -> Black, 1 -> Yellow, 2 -> Orange},
 PixelConstrained -> 2,
 Frame -> False
]

This makes every point on the plot a 2px by 2px square.
For full control this can be done manually with Raster and Offset:
data /. {0 -> {0, 0, 0}, 1 -> {1, 1, 0}, 2 -> {1, 0.5, 0}};
Graphics[Raster[Reverse @ %, {{0, 0}, Offset[{322, 162}, {0, 0}]}],
 ImageSize -> {322, 162}, PlotRange -> {{0, 322}, {0, 162}}, Frame -> False,
 FrameTicks -> None]

With either method you will find that adding frame ticks causes clipping as the ImageSize does not account for the label area.  A solution is to specify the ImagePadding manually and include it in the ImageSize.
myPlot[data_, scale_Integer, pad_Integer:0, opts : OptionsPattern[]] :=
 With[{size = scale {#2, #} & @@ Dimensions@data},
  Graphics[Raster[Reverse @ data, {{0, 0}, Offset[size, {0, 0}]}],
   ImageSize -> 2 + pad + size,
   PlotRange -> {{0, size[[1]]}, {0, size[[2]]}}, opts,
   ImagePadding -> {{pad, 1}, {pad, 1}},
   PlotRangeClipping -> True, Frame -> True,
   FrameTicks -> None
  ]
 ]

data /. {0 -> {0, 0, 0}, 1 -> {1, 1, 0}, 2 -> {1, 0.5, 0}};
myPlot[%, 2, 25, FrameTicks -> True]

A: The direct approach to the problem is to take the Raster expression directly from the generated Graphics object and then convert it to an Image object by applying Image to Raster (not to Graphics!).
As Documentation says, "Image[Raster[...]] converts a Raster object to an image."
The solution is as follows:
data = CellularAutomaton[{1635, {3, 1}}, {{1}, 0}, 80];
pl = ArrayPlot[data, ColorRules -> {0 -> Black, 1 -> Yellow, 2 -> Orange}];

Export["MatrixExportFileExample.tiff", Image@pl[[1]]];

The PixelConstrained option of ArrayPlot does not change the Image@pl[[1]]. You will get pixel-perfect image with guarantee. Note however that this approach imply that the Graphics object generated (pl) contains only one graphics primitive: Raster, as it is by default. If you wish to add other primitives (or wish to include ticks in the rasterized image), Mr.Wizard's solution is a way to go. Some additional explanations can be found here.


text:
Q: How can I set a minimum password length when using the built-in Django auth module? I'm implementing authentication in a Django site using the built-in auth module, including the built-in UserCreationForm.
I'd like to set a minimum length for passwords. However, I can't find any documentation on how to do this.
Can I configure the auth module's User module to require this at the database level? Or should I sub-class the UserCreationForm (I'm actually doing this already for unrelated reasons) and add an extra validator that enforces the password length?

A: Especially if you're already using a sub-classed UserCreationForm, I'd say you should definitely just add the validation to it. You should be able to override the clean_password method on the form:
def clean_password(self):
    password = self.cleaned_data.get('password1')
    if len(password) < 8:
        raise ValidationError('Password too short')
    return super(MyUserCreationForm, self).clean_password1()

A: I think the easiest way to achieve this is using Django password validation
For minimum length would be enough adding this to settings file:
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
]

There are others validators like NumericPasswordValidator and CommonPasswordValidator

A: Subclassing the user creation form sounds like a good approach. You can't enforce it at the database level, since Django only stores a hash of the password.

A: Some info about answers,
django.contrib.auth.password_validation.MinimumLengthValidator

was newly implemented from django 1.9+ for older version it wont work,
so you can go with your own custom validator,
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext

def validate(min_length, password):
    special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]"
    if len(password) < 8:
        raise ValidationError(ugettext('Password length must be greater than 8 character.'))
    if not any(char.isdigit() for char in password):
        raise ValidationError(ugettext('Password must contain at least %(min_length)d digit.') % {'min_length': min_length})
    if not any(char.isalpha() for char in password):
        raise ValidationError(ugettext('Password must contain at least %(min_length)d letter.') % {'min_length': min_length})
    if not any(char in special_characters for char in password):
        raise ValidationError(ugettext('Password must contain at least %(min_length)d special character.') % {'min_length': min_length})

A: /django/contrib/auth/password_validation.py Contains class MinimumLengthValidator with default the password minimum length:
class MinimumLengthValidator(object):
    """
    Validate whether the password is of a minimum length.
    """
    def __init__(self, min_length=8):
        self.min_length = min_length

    def validate(self, password, user=None):
        if len(password) < self.min_length:
            raise ValidationError(
                ungettext(
                    "This password is too short. It must contain at least %(min_length)d character.",
                    "This password is too short. It must contain at least %(min_length)d characters.",
                    self.min_length
                ),
                code='password_too_short',
                params={'min_length': self.min_length},
            )

    def get_help_text(self):
        return ungettext(
            "Your password must contain at least %(min_length)d character.",
            "Your password must contain at least %(min_length)d characters.",
            self.min_length
        ) % {'min_length': self.min_length}


text:
Q: Выборка из таблицы поля с двумя значениями Привет всем у меня стоит такая задача нужно реализовать фильтр товаров по характеристикам, запрос формируется вот к такой табличке
id---product_id---option_id---option_value
1 ---   1      --- 1 --- 10
2 ---   1      --- 2 --- 15
3 ---   2      --- 1 --- 20
4 ---   2      --- 2 --- 15

вопрос в том как построить запрос чтобы вытащить допустим только тот товар с весом 20 и размером 15
пусть option_id = 1 будет вес а option_id = 2 размер
помогите допиреть как построить запрос
я смог построить такой запрос в случае если выберется товар по задоному мной условию все работает как часы
SELECT product_id FROM products_rels WHERE oprion_id in(3,1) and option_value in(15,10) group by 1 HAVING COUNT(*)=2
Но если поменять условия и скажем выбрать
SELECT product_id FROM products_rels WHERE oprion_id in(1) and option_value in(10) group by 1 HAVING COUNT(*)=2
результат выдает ноль строк на сделать запрос более универсальным?

A: Из того что я понял попытаюсь составить запросы...
Выбирает все товары у которых вес 20 ИЛИ размер 15:
SELECT `product_id` FROM `products_rels` WHERE
(`option_id` = 1 AND `option_value` = 20)
OR
(`option_id` = 2 AND `option_value` = 15)

Выбирает все товары у которых вес 20 И размер 15:
SELECT `product_id` FROM `products_rels` WHERE
(`option_id` = 1 AND `option_value` = 20)
AND
(`option_id` = 2 AND `option_value` = 15)

Выбирает все товары у которых вес 20 И размер 15, группирует по product_id:
SELECT `product_id` FROM `products_rels` WHERE
(`option_id` = 1 AND `option_value` = 20)
AND
(`option_id` = 2 AND `option_value` = 15)
GROUP BY `product_id`

A: читайте про sql конструкцию WHERE
SELECT ... FROM ... WHERE item_weight = 20 and item_size = 15


text:
Q: Scrapy-TypeError: Cannot mix str and non-str arguments error I am new in Python and i am following the tutorial and i got this error.
When i run scrapy it says typeerror:cannot mix str and non-str arguments Can you help me please
Thank you in advance.
class ForRentSpider(scrapy.Spider):
name = 'for_rent'
allowed_domains = ['www.laforet.com/']
start_urls = ['https://www.laforet.com/louer/rechercher']

def parse(self, response):
    houses = response.xpath("//div[@class='list-item mb-6 col-lg-6 col-xl-3']/div/a")

    for house in houses:
        title = house.xpath(".//div[@class='d-flex justify-content-between']/h4/text()").get(),
        link = response.urljoin(house.xpath(".//@href").get()),
        metre = house.xpath("normalize-space(.//div[@class='property-card__infos']/div/span/text())").get(),
        room = house.xpath("normalize-space(.//div[@class='property-card__infos']/div/span[2]/text())").get(),
        price = house.xpath("normalize-space(.//div[@class='property-card__infos']/span/text())").get()

        yield response.follow(url=link, callback=self.parse_house, meta={'house_title': title, 'house_metrekare': metre, 'house_room': room, 'house_price': price})

def parse_house(self, response):
    title = response.request.meta['house_title']
    metre = response.request.meta['house_metrekare']
    room = response.request.meta['house_room']
    price = response.request.meta['house_price']
    infos = response.xpath("//div[@class='property-content__description mb-4']")

    for info in infos:
        house_info = info.xpath(".//div[@class='mb-2']/text()").get()

        yield{
            'house_title': title,
            'house_metrekare': metre,
            'house_room': room,
            'house_price': price,
            'info': house_info

        }

A: Welcome to Stack Overflow. In the future, please include you execution logs in this type of questions, as they help us to understand the issue.
The problem in your code is that you are passing a tuple in the variable link, when it should be a string. The reason for that is that you are adding a comma at the end of the variable definition, for no apparent reason.
    link = response.urljoin(house.xpath(".//@href").get()),

Python interprets this as a tuple of a single value. Removing the , at the end of the line will solve your problem.
There are other lines in your code doing the same, if you don't want those variables to be tuples you should remove the , at the end of their lines as well. They won't cause an issue though, as they are not used in the request method.


text:
Q: clickhouse client is going down beacuse of query on Materialized Views when creating mv with the target table
target table:
CREATE TABLE target_test
(
    day date,
    hour UInt32,
    test_sum SimpleAggregateFunction(sum, Float64)
)
ENGINE = SummingMergeTree()
PARTITION BY toRelativeWeekNum(toDateTime(day))
ORDER BY (day, hour)

CREATE MATERIALIZED VIEW target_test_mv
TO target_test
as select
toDate(session_ts) as day,
toHour(toDateTime(session_ts)) as hour,
sum(if (test is null, 0,test)) as test_sum
from events
where session_ts>= now()-1000
group by day, hour

when the data is inserting into the target table and when I am running this query
clickhouse server is crashed because of the query why??
select sum(revenue_sum) from target_test_mv

this is from the log :
2020.12.07 12:03:48.059559 [ 19243 ] {} <Fatal> BaseDaemon: ########################################
2020.12.07 12:03:48.059595 [ 19244 ] {} <Fatal> BaseDaemon: ########################################
2020.12.07 12:03:48.059642 [ 19244 ] {} <Fatal> BaseDaemon: (version 20.4.2.9 (official build)) (from thread 19242) (query_id: 6651689c-484a-4b53-a174-06fd01848208) Received signal Segmentation fault (11).
2020.12.07 12:03:48.059644 [ 19243 ] {} <Fatal> BaseDaemon: (version 20.4.2.9 (official build)) (from thread 19241) (query_id: 6651689c-484a-4b53-a174-06fd01848208) Received signal Segmentation fault (11).
2020.12.07 12:03:48.059685 [ 19244 ] {} <Fatal> BaseDaemon: Address: NULL pointer. Access: read. Address not mapped to object.
2020.12.07 12:03:48.059691 [ 19243 ] {} <Fatal> BaseDaemon: Address: NULL pointer. Access: read. Address not mapped to object.
2020.12.07 12:03:48.059710 [ 19244 ] {} <Fatal> BaseDaemon: Stack trace: 0xcad040b 0xd26b20d 0xd281202 0xdcbb2f3 0xdcbf909 0xdb0b9a1 0xdb0f95d 0xdb10324 0x901e26b 0x901c753 0x7fec413f0dd5 0x7fec41a04ead
2020.12.07 12:03:48.059712 [ 19243 ] {} <Fatal> BaseDaemon: Stack trace: 0xcad040b 0xd26b20d 0xd281202 0xdcbb2f3 0xdcbf909 0xdb0b9a1 0xdb0f95d 0xdb10324 0x901e26b 0x901c753 0x7fec413f0dd5 0x7fec41a04ead
2020.12.07 12:03:48.059781 [ 19244 ] {} <Fatal> BaseDaemon: 3. DB::IAggregateFunctionHelper<DB::AggregateFunctionNullUnary<true> >::addBatchSinglePlace(unsigned long, char*, DB::IColumn const**, DB::Arena*) const @ 0xcad040b in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse
2020.12.07 12:03:48.059781 [ 19243 ] {} <Fatal> BaseDaemon: 3. DB::IAggregateFunctionHelper<DB::AggregateFunctionNullUnary<true> >::addBatchSinglePlace(unsigned long, char*, DB::IColumn const**, DB::Arena*) const @ 0xcad040b in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse
2020.12.07 12:03:48.059856 [ 19243 ] {} <Fatal> BaseDaemon: 4. DB::Aggregator::executeWithoutKeyImpl(char*&, unsigned long, DB::Aggregator::AggregateFunctionInstruction*, DB::Arena*) @ 0xd26b20d in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse
2020.12.07 12:03:48.059858 [ 19244 ] {} <Fatal> BaseDaemon: 4. DB::Aggregator::executeWithoutKeyImpl(char*&, unsigned long, DB::Aggregator::AggregateFunctionInstruction*, DB::Arena*) @ 0xd26b20d in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse
2020.12.07 12:03:48.059902 [ 19243 ] {} <Fatal> BaseDaemon: 5. DB::Aggregator::executeOnBlock(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::immutable_ptr<DB::IColumn> > >, unsigned long, DB::AggregatedDataVariants&, std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> >&, std::__1::vector<std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> >, std::__1::allocator<std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> > > >&, bool&) @ 0xd281202 in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse
2020.12.07 12:03:48.059917 [ 19244 ] {} <Fatal> BaseDaemon: 5. DB::Aggregator::executeOnBlock(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::__1::allocator<COW<DB::IColumn>::immutable_ptr<DB::IColumn> > >, unsigned long, DB::AggregatedDataVariants&, std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> >&, std::__1::vector<std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> >, std::__1::allocator<std::__1::vector<DB::IColumn const*, std::__1::allocator<DB::IColumn const*> > > >&, bool&) @ 0xd281202 in /opt/clickhouse/engine/clickhouse-common-static-20.4.2.9/usr/bin/clickhouse

A: I've tried a scenario similar to yours in a more recent version of ClickHouse and it works for me:
CREATE TABLE target_test
    ( day date,
    hour UInt32,
    test_sum Float64 )
ENGINE = SummingMergeTree() PARTITION BY toRelativeWeekNum(toDateTime(day)) ORDER BY (day, hour)

CREATE MATERIALIZED VIEW target_test_mv TO target_test as
select
    toDate(event_time) as day,
    toHour(toDateTime(event_time)) as hour,
    sum(if (read_rows is null, 0,read_rows)) as test_sum
from system.query_log
group by day, hour
limit 10000

:) select sum(test_sum) from target_test;

SELECT sum(test_sum)
FROM target_test

┌─sum(test_sum)─┐
│         20661 │
└───────────────┘

Note I'm using the query_log for the test and I've removed the SimpleAggregateFunction since the SummingMergeTree takes care of that.
You could try several things:

*

*Try to reproduce the scenario above with the system.query_log instead of your events table, to discard there's any problem with your table.

*Try on a more recent version of ClickHouse (20.4.2.9 is from May)

*If your scenario still fails and given there's a segmentation fault in the logs, you can open a case in the ClickHouse GitHub repo.


text:
Q: Convert ZIP file structure to treeview recursively I have been wondering if there is anyway to make my code below function in a recursive fashion.
I did look at some examples here at Stack Overflow but they all seem to be solely dealing with existing file structures on a local drive.
Zip files have no file structure. Only lists of full paths.
Before I get blasted for not posting any attempts at coding this, I have no idea how to do it. Recursion is voodoo magic I have never been able to code correctly with out example work.
Below is a solution I worked out. If anyone has been trying to sort this out.. Try this. It works but only will handle 8 levels of nesting. It can be expanded easy enough once you understand how the code works.
If this can be converted in to something more compact and possibly faster, I'd like to try and code it with some guidance.
Module modZipFolderResolver
Public root As root_
Public Structure root_
    Public node() As root_
    Public name As String
    Public index As Integer
    Public isDir As Boolean
    Public count As Integer
    Dim n As TreeNode
    Public Function find(f As String, ByRef idx As Integer)
        If node Is Nothing Then
            Return False
        End If
        For k = 0 To Me.node.Length - 1
            If node(k).name = f Then
                idx = k
                Return True
            End If
        Next
        Return False
    End Function
    Public Sub add(ByRef s As String, ByRef idx As Integer, ByVal fullname As String, ByRef p_node As TreeNode, ByVal isDir As Boolean)
        ReDim Preserve Me.node(Me.count + 1)
        idx = Me.count
        node(Me.count) = New root_
        node(Me.count).name = s
        '------------------------------------
        'add node
        Dim nn As New TreeNode 'create new treevire node
        nn.Tag = fullname
        nn.Text = Me.node(Me.count).name
        If isDir Then ' set image index based on type
            Me.node(Me.count).isDir = True
            nn.SelectedImageIndex = 2
            nn.ImageIndex = 2
            nn.Name = "dir" 'used for evauation when clicked
        Else
            Me.node(Me.count).isDir = False
            nn.SelectedImageIndex = 1
            nn.ImageIndex = 0
            nn.Name = ""
        End If
        '------------------------------------
        ' make a new one if its blank
        If p_node Is Nothing Then
            p_node = New TreeNode
            p_node.Text = Me.name
        End If
        Me.node(Me.count).n = New TreeNode
        Me.node(Me.count).n = nn
        p_node.Nodes.Add(Me.node(Me.count).n)
        '------------------------------------
        Me.count += 1
    End Sub
End Structure

Public Sub build_tree()
    '--------------------------------------------------------
    'create the root node
    root = New root_
    GC.Collect() ' clean up garbage if we just killed existing data
    root.n = New TreeNode
    root.n.SelectedImageIndex = 2
    root.n.ImageIndex = 2
    root.n.Text = frmTreeList.tv_filenames.SelectedNode.Text
    root.n.Name= "dir"
    frmTreeList.tv_contents.Nodes.Add(root.n) 'Add to treeview
    '--------------------------------------------------------
    'now the fun up part. Create the nested tree structure.
    Dim indexes(9) As Integer 'used to keep track of where we are in the tree structure
    Dim isDir As Boolean = False ' flag for setting up image index
    For Each ent In current_package
        Dim ext = Path.GetExtension(ent.FileName)
        If ext.Length > 0 Then 'is this entry a file or directory?
            isDir = False
        Else
            isDir = True
        End If
        Dim a = ent.FileName.Split("/")
        For i = 0 To 8 ' 8 levels deep enough?
            If a.Length = 2 Then
                Exit For
            End If
            If i > a.Length - 1 Then
                Exit For
            End If
            For k = i To a.Length - 1
                If a(k) = "" Then
                    Exit For
                End If
                Dim idx As Integer
                Select Case k
                    Case 0
                        If root.find(a(0), idx) Then
                            indexes(0) = idx
                        Else
                            root.add(a(0), idx, ent.FileName, root.n, isDir)
                            indexes(0) = idx
                            Exit For
                        End If
                    Case 1
                        If root.node(indexes(0)).find(a(1), idx) Then
                            indexes(1) = idx
                        Else
                            Dim n = root.node(indexes(0)).n
                            root.node(indexes(0)).add(a(1), idx, ent.FileName, n, isDir)
                            indexes(1) = idx
                            Exit For
                        End If
                    Case 2
                        If root.node(indexes(0)).node(indexes(1)).find(a(2), idx) Then
                            indexes(2) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).n
                            root.node(indexes(0)).node(indexes(1)).add(a(2), idx, ent.FileName, n, isDir)
                            indexes(2) = idx
                            Exit For
                        End If
                    Case 3
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).find(a(3), idx) Then
                            indexes(3) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).add(a(3), idx, ent.FileName, n, isDir)
                            indexes(3) = idx
                            Exit For
                        End If
                    Case 4
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).find(a(4), idx) Then
                            indexes(4) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).add(a(4), idx, ent.FileName, n, isDir)
                            indexes(4) = idx
                            Exit For
                        End If
                    Case 5
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).find(a(5), idx) Then
                            indexes(5) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).add(a(5), idx, ent.FileName, n, isDir)
                            indexes(5) = idx
                            Exit For
                        End If
                    Case 6
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).find(a(6), idx) Then
                            indexes(6) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).add(a(6), idx, ent.FileName, n, isDir)
                            indexes(6) = idx
                            Exit For
                        End If
                    Case 7
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).find(a(7), idx) Then
                            indexes(7) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).add(a(7), idx, ent.FileName, n, isDir)
                            indexes(7) = idx
                            Exit For
                        End If
                    Case 8
                        If root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).node(indexes(7)).find(a(8), idx) Then
                            indexes(8) = idx
                        Else
                            Dim n = root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).node(indexes(7)).n
                            root.node(indexes(0)).node(indexes(1)).node(indexes(2)).node(indexes(3)).node(indexes(4)).node(indexes(5)).node(indexes(6)).node(indexes(7)).add(a(8), idx, ent.FileName, n, isDir)
                            indexes(8) = idx
                            Exit For
                        End If
                End Select
            Next 'k
        Next 'i
    Next 'each ent
End Sub
End Module

This code works well and produces a treeview like this. i'm just hoping someone can shed light on maybe speeding this up using recursion.

A: In terms of an algorithm, I would do it as follows: -
For each path: -
Split the path into an array of strings by the "/" character.
Pass this array into a new function along with the root node and an index of 0, to indicate that that is where you are up to.
The function should: -
Get the path component for the index passed in
Find or create the child node within the node passed in as a parameter that matches the path component
If the index passed in is equal to the length of the path component array -1 then return the found/created child node
Else the function should return the result of a call to itself, passing in the child node and the index which was passed in +1
This function should create nodes as needed and return the Node for the path

A: I found a solution though it seems to be just slightly slower. Probably because of having to return back through the call stack. I'll setup a timer and call the old version and the new one and I'll use the fastest version.
This is not limited to just zip files.. any list of file paths will generate a correctly built TreeView.
The advantage of the new method is, there is no limit to the depth of nesting where, the old version is limited to 8 unless the code is expanded.
Just had a idea.. Check how deep the split array of the path is and if its over 8 call the new version, otherwise, call the old version.
UPDATE: I did some time studies and the new version IS slower.
The results of different sized zip files
==================================
Path Count: 10756
New method: 0.328ms
Old method: 0.275ms

==================================
Path Count: 11860
New method: 0.338ms
Old method: 0.287ms

==================================
Path Count: 06672
New method: 0.189ms
Old method: 0.177ms

==================================
Path Count: 01168
New method: 0.032ms
Old method: 0.027ms

The new Method code:
Public Sub build_tree_recrusive()
    '--------------------------------------------------------
    'create the root node
    root = New root_
    GC.Collect() ' clean up garbage if we just killed existing data
    root.n = New TreeNode
    root.n.SelectedImageIndex = 2
    root.n.ImageIndex = 2
    root.n.Text = frmTreeList.tv_filenames.SelectedNode.Text
    root.n.Name = "dir"
    frmTreeList.tv_contents.Nodes.Add(root.n) 'Add to treeview
    '--------------------------------------------------------
    'now the fun up part. Create the nested tree structure.
    Dim indexes(9) As Integer 'used to keep track of where we are in the tree structure
    Dim isDir As Boolean = False ' flag for setting up image index
    For Each ent In current_package
        Dim ext = Path.GetExtension(ent.FileName)
        If ext.Length > 0 Then 'is this entry a file or directory?
            isDir = False
        Else
            isDir = True
        End If
        Dim a = ent.FileName.Split("/")

        rc(a, 0, 0, root, ent.FileName, isDir)

    Next 'each ent
End Sub
Private Function rc(ByRef a() As String, ByRef idx As Integer, ByRef ndx As Integer, ByRef node As root_, ByRef fullpath As String, ByVal isDir As Boolean) As Boolean
    If idx = a.Length Then Return True
    If a(idx) = "" Then Return True
    If node.find(a(idx), ndx) Then
        If rc(a, idx + 1, ndx, node.node(ndx), fullpath, isDir) Then
            Return True
        End If
    Else
        node.add(a(idx), ndx, fullpath, node.n, isDir)
        If rc(a, idx + 1, ndx, node.node(ndx), fullpath, isDir) Then
            Return True
        End If
    End If
    Return True
End Function


text:
Q: How to stop ioloop in pyzmq correctly and completely to free up sockets? I'm trying to create high level interface to zmq in python
Here is what it looks like
from abc import ABCMeta, abstractmethod
import zmq
from abstracts.BaseMessagingNode import BaseMessagingNode

__author__ = 'michael'

class BaseZmqNode():
    __metaclass__ = ABCMeta

    def __init__(self, host, port,  bind, hwm):
        self.node = self.create_node()
        self.node.host = host
        self.port = port
        self.context = zmq.Context().instance()
        self.socket = self.create_socket()
        if bind:
            self.socket.bind(self.build_address(host, port))
        else:
            self.socket.connect(self.build_address(host, port))
        self.set_hwm(hwm)

    def set_hwm(self, hwm):
        self.socket.set_hwm(hwm)

    def send_multipart(self, message):
        self.socket.send_multipart(message)

    def send_json(self, json):
        self.socket.send_json(json)

    def create_node(self):
        return BaseMessagingNode

    def close(self):
        self.socket.close()

    @staticmethod
    def build_address(host, port):
        strings = [host, ':', str(port)]
        return ''.join(strings)

    @abstractmethod
    def create_socket(self):
        pass

from abc import ABCMeta
from zeromq.ZmqLoopRunner import ZmqLoopRunner
from zmq.eventloop.zmqstream import ZMQStream
from abstracts.ReceivingNode import ReceivingNode
from zeromq.BaseZmqNode import BaseZmqNode

__author__ = 'michael'

class BaseZmqReceiver(BaseZmqNode):

    __metaclass__ = ABCMeta

    def __init__(self, host, port, hwm, bind, on_receive_callback):
        super(BaseZmqReceiver, self).__init__(host=host, port=port, bind=bind, hwm=hwm)
        self.node.on_message_callback = on_receive_callback
        self.stream = ZMQStream(self.socket)
        self.stream.on_recv(self.on_message_received)
        self.runner = ZmqLoopRunner()
        self.runner.start()

    def on_message_received(self, message):
        return self.node.on_message_callback(message)

    def create_node(self):
        return ReceivingNode(None, None)

    def close(self):
        # super(BaseZmqReceiver, self).close()

        self.runner.stop()
        self.stream.close()
        # self.socket.close()

from threading import Thread
from zmq.eventloop import IOLoop

__author__ = 'michael'
class ZmqLoopRunner(Thread):

    def __init__(self):
        super(ZmqLoopRunner, self).__init__()
        self.loop = IOLoop.current()

    def run(self):
        self.loop.start()

    def stop(self):
        self.loop.add_callback(self.loop.stop)

So basically I'm trying to run ioloop in separate thread so it won't block the application that's using zmq for communication.
I have a set of test which all passed by my code. But in one out of three runs I have this exception. I don't even know where to start...
 File "/opt/leos/code/messaging_system/zeromq/ZmqLoopRunner.py", line 12, in run
    self.loop.start()
  File "/Library/Python/2.7/site-packages/zmq/eventloop/ioloop.py", line 160, in start
    super(ZMQIOLoop, self).start()
  File "/Library/Python/2.7/site-packages/tornado/ioloop.py", line 646, in start

    event_pairs = self._impl.poll(poll_timeout)
  File "/Library/Python/2.7/site-packages/zmq/eventloop/ioloop.py", line 132, in poll
    z_events = self._poller.poll(1000*timeout)

  File "/Library/Python/2.7/site-packages/zmq/sugar/poll.py", line 110, in poll
    return zmq_poll(self.sockets, timeout=timeout)
  File "_poll.pyx", line 125, in zmq.backend.cython._poll.zmq_poll (zmq/backend/cython/_poll.c:1705)
IndexError: list index out of range

I think that the problem is that loop is not completely closed by the moment socket and stream are closed.

A: As per the docs there are 2 approaches to start a IOLoop:

*

*Explicitly call make_current() before starting the loop and after creating the self.loop to set the correct instance

*Or, use IOLoop.instance() rather than using IOLoop.current() to get a valid instance. This will make sure you have an instance of IOLoop.

Note: I haven't tried it but suspect this as the problem. Hopefully this helps !


text:
Q: How to get data from another page (different servers) I want to make a IE8 web slice who will show remaining amount of students "food credit". In our country we have web page where we can see amount www.cap.srce.hr/ProvjeraSaldo.aspx. When I fill textbox with my card number I receive remaining amount. Now, I want to speed that process with IE8 web slice. So is it possible to get data from another webserver page and than display it in my web slice on my web server. I tried to use XMLHTTP request but it can be only used on same domains. Url for getting amount is :
http://www.cap.srce.hr/saldo.aspx?brk={number_of_card}

A: Several ways, depending on your situation:

*

*As an IFRAME (if you get the other
server to render HTML instead of
Javascript)

*As JSONP

*Through a server-side proxy

*Through a Flash bridge (which would require a crossdomain.xml on the other server)

A: Tnx Malvolio. I found other solution using ASP.NET. More info on this page : http://www.csharp-station.com/HowTo/HttpWebFetch.aspx . After you fetch web page source you can try parse elements using Regex or I found more easy way using great library HtmlAgilityPack (http://htmlagilitypack.codeplex.com/)


text:
Q: Calculate edits in QuickTime Movie File with Edit List Atom In a Linux environment, is there a way to calculate any edits in a QuickTime Movie File track? Specifically, I need duration and start time of edits in relation to the movie.
I have been parsing the raw mov file to look at the Edit List Atom ( i.e. 'elst' ) to get the track duration and media time but, even after the adjustments for time scale units the start time always seems off.
For example, I have a single track video which has been edited to have first and last 6 seconds of the video removed. However, when I look at the 'elst' atom of that file the track duration is the length of the new file but, the media time does not match what I would have expected (i.e. something equivalent to 6 seconds).
I have tried looking into tools like FFmpeg but have had little success.


text:
Q: how to change value in a specific memory address? I'm new to c programming. There is a use case: I need to change value in a specific memory address.
int main(){

    int *p;
    p = 0x111;
    *p = 100;
    return 0;
}

However, I cannot compile the above code. It shows the following problem.
test.c:10:7: warning: incompatible integer to pointer conversion assigning to 'int *' from 'int' [-Wint-conversion]
    p = 0x111;
      ^ ~~~~~
1 warning generated.

I tried casting like following:
int main(){

    int *p;
    p = (int *) 0x111;
    *p = 100;
    return 0;
}

It can compile, however, when I run it, it shows segmentation fault.
My Question:

*

*Is there a way that I can forcedly compile and run this code? I know there is wild pointer problem. However, it's a common use case to manipulate memory. For example, when I play a local game. Somehow, I know the specific memory address of my player's health point when the game is running, e.g. address = 0x123. How to just change the value in 0x123?

*If I cannot use above way to manipulate value in any specific memory address, is there other standard way to realize my use case?
PS:
By the way, I found the example way to realize my use case.
You can refer to the source code: https://github.com/haseeb-heaven/GTLibc/
How do game trainers change an address in memory that's dynamic?
https://www.youtube.com/watch?v=cRCnN987gd8&ab_channel=HaseebMir

A: Given a valid pointer to an object in a memory address, indirect through the pointer and assign a value:
int health_points = 1337;  // an object in some memory address
int* ptr = &a;             // pointer to the value in that memory address
*ptr = 0;                  // the value is modified

Is there a way that I can forcedly compile and run this code?

Your program is ill-formed. There may be a way to let a compiler successfully compile it if the compiler provides a relevant language extension, but it is typically a bad idea to rely on such extensions because it would trap you into using that one compiler.
Instead of trying to force a compiler accept a broken program, I recommend fixing the program.

how to change value in a specific memory address?

Firstly, the memory in that address must be allocated. The language implementation takes care of allocating all memory and there is no standard way to specify what address is allocated.
However, some language implementations may specify certain addresses as accessible. This is typical on embedded systems. If this is the case, then you can convert an integer value to a pointer using a cast:
std::uintptr_t address = 0x111; // see documentation whether this is a valid address
int* ptr = reinterpret_cast<int*>(address);

If your language implementation doesn't specify that the address is accessible, then there are no guarantees about accessing it. On modern operating systems which manage virtual memory, the best case scenario is a segfault.

A: Let me make you understand how applications reads address of another application or self.

*

*Self address.
The address you are reading has be above base address which is 0x0040000 for executable image so it should look like this 0x0040000 + 0x0040 where 0x0040 is the offset from base address.
And if you accessing region other than .text(Read only) the you have to change the permission of the region first using VirtualProtect method as shown here

*External application address.
If you want to read address from external application lets say your game then first you have to get the Application Handle which is just and identifier for your application and then use ReadProcessMemory as shown here similarly you can write also using WriteProcessMemory as shown here
Just always make sure you don't access other than .text section without changing its permission region otherwise your program could crash.


text:
Q: Parse error: syntax error, unexpected 'layouts' (T_STRING), expecting ',' or ') I'm working on a view in a laravel project (full project is available on github at https://github.com/wvulibraries/rockefeller-css/tree/trying-searchy/src/project-css) what I want to do is identify if the string contains a filename with a .txt extension and then strip out the path from the string. Leaving just filename.txt. We are importing a csv file and the path is going to be different for the file. What we want to to is load the files into a folder in storage and let the users click to view the file. An example from one record is "..\documents\BlobExport\formletters\vecr0601_concurrent_receipt.txt". I was going to try to use
$filename = end(explode('\',$rcrd->$clmnNme));

but it crashes the view ever time and gives "Parse error: syntax error, unexpected 'layouts' (T_STRING), expecting ',' or ')' (View: /var/www/html/project-css/resources/views/user/show.blade.php)". The current view is below.
@extends('layouts.default')

@section('content')

@include('user/searchbox');

      @foreach($rcrds as $key => $rcrd)

          @foreach($clmnNmes as $key => $clmnNme)
            @if (strpos($rcrd->$clmnNme, '.txt') !== FALSE)
              @php
                $filename = end(explode("\", $rcrd->$clmnNme));
              @endphp

{{$clmnNme}}: {{$rcrd->$clmnNme}} {{$filename}}

            @else

{{$clmnNme}}: {{$rcrd->$clmnNme}}

            @endif
          @endforeach

      @endforeach

@endsection

The database cannot change it is being used for research so I cannot change it during the import. Any help would be appreciated.

A: By using backslash, you escape character and that's why you have an error:
//Correct
$tokens = explode('\\',$rcrd->$clmnNme);
$filename = end($tokens);

//Wrong
$filename = end(explode('\',$rcrd->$clmnNme)); //Wrong

You can also see this from code highlighter that something looks odd.


text:
Q: lwjgl 3: No GLCapabilities instance set for the current thread. glCreateProgram() I can not solve the problem in question. I tried several solutions to this error but without any positive result. If i try to remove glCreateProgram() method the error move to glCreateShader() method.
Error
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException: No GLCapabilities instance set for the current thread. Possible solutions:
    a) Call GL.createCapabilities() after making a context current in the current thread.
    b) Call GL.setCapabilities() if a GLCapabilities instance already exists for the current context.
    at org.lwjgl.opengl.GL.getCapabilities(GL.java:238)
    at org.lwjgl.opengl.GL20.glCreateProgram(GL20.java:209)
    at ms.shaders.ShaderProgram.<init>(ShaderProgram.java:18)
    at ms.shaders.Shaders.<init>(Shaders.java:8)
    at ms.renderer.Renderer.<init>(Renderer.java:13)
    at ms.main.MainGame.<clinit>(MainGame.java:16)

ShaderProgram
package ms.shaders;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public abstract class ShaderProgram {

    private int programID;
    private int vShaderID;
    private int fShaderID;

    public ShaderProgram(String vShader, String fShader)  {

        programID = glCreateProgram(); //Error line

        String vertexShaderSource = loadShader(vShader);

        vShaderID = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vShaderID, vertexShaderSource);

        glCompileShader(vShaderID);

        if (glGetShaderi(vShaderID, GL_COMPILE_STATUS) == GL_FALSE) {
            throw new RuntimeException("Error creating vertex shader\n"
                    + glGetShaderInfoLog(vShaderID, glGetShaderi(vShaderID, GL_INFO_LOG_LENGTH)));
        }

        glAttachShader(programID, vShaderID);

        String fragmentShaderSource = loadShader(vShader);

        fShaderID = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fShaderID, fragmentShaderSource);

        glCompileShader(fShaderID);

        if (glGetShaderi(fShaderID, GL_COMPILE_STATUS) == GL_FALSE) {
            throw new RuntimeException("Error creating vertex shader\n"
                    + glGetShaderInfoLog(fShaderID, glGetShaderi(fShaderID, GL_INFO_LOG_LENGTH)));
        }

        glAttachShader(programID, vShaderID);
    }

    protected abstract void bindAttribute();

    protected void bindAttribute(int attribute, String name) {
        glBindAttribLocation(programID, attribute, name);
    }

    public void link() {

        glLinkProgram(programID);

        if(glGetProgrami(programID, GL_LINK_STATUS) == GL_FALSE) {
            throw new RuntimeException("Failed to link program: ");
        }
    }

    public void validate() {

        glValidateProgram(programID);

        if(glGetShaderi(programID, GL_VALIDATE_STATUS) == GL_FALSE) {
            throw new RuntimeException("Failed to validate program: ");
        }
    }

    public void bind() {
        glUseProgram(programID);
    }

    public void unbind() {
        glUseProgram(0);
    }

    public void dispose() {

        unbind();

        glDetachShader(programID, vShaderID);
        glDetachShader(programID, fShaderID);
        glDeleteShader(vShaderID);
        glDeleteShader(fShaderID);
        glDeleteProgram(programID);
    }

    private static String loadShader(String file) {

        StringBuilder shaderSource = new StringBuilder();

        try {

            BufferedReader reader = new BufferedReader(new FileReader(file));

            String line;

            while((line = reader.readLine()) != null) {
                shaderSource.append(line).append("//\n");
            }

            reader.close();

        } catch(IOException e){
            e.printStackTrace();
            System.exit(-1);
        }

        return shaderSource.toString();
    }
}

Renderer
package ms.renderer;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import ms.renderer.VertexArrayObject.Vertex;
import ms.shaders.Shaders;

public class Renderer {

    VertexArrayObject vertex = new VertexArrayObject();
    Shaders shaders = new Shaders();

    public void prepare() {

        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    }

    public void render(Vertex vertex) {

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        shaders.bind();

        glBindVertexArray(vertex.getVaoID());
        glEnableVertexAttribArray(0);

        glDrawElements(GL_TRIANGLES, vertex.getVertexCount(), GL_UNSIGNED_INT, 0);

        glDisableVertexAttribArray(0);
        glBindVertexArray(0);

        shaders.unbind();
    }

    public void clear() {

        shaders.dispose();
        vertex.cleanUp();
    }
}

MainGame
package ms.main;

import static org.lwjgl.glfw.GLFW.*;

import ms.input.KeyboardInput;
import ms.renderer.Renderer;
import ms.renderer.VertexArrayObject;
import ms.renderer.VertexArrayObject.Vertex;
import ms.utils.FinalVariables;

public class MainGame implements Runnable {

    private Thread thread;

    private static Display display = new Display();
    private static Renderer renderer = new Renderer();
    private static VertexArrayObject loader = new VertexArrayObject();

    private static int WIDTH = FinalVariables.WIDTH;
    private static int HEIGHT = FinalVariables.HEIGHT;
    private static String TITLE = FinalVariables.TITLE;

    private boolean isRunning = false;

    public static void main(String[] args) {

        MainGame game = new MainGame();

        display = new Display(WIDTH, HEIGHT, TITLE);
        game.start();
    }

    public void start() {

        isRunning = true;

        thread = new Thread(this, "MainThread");
        thread.start();
    }

    public void run() {

        display.init();
        display.libVersion();

        float[] positions = new float[]{

                -0.5f,  0.5f, 0.0f,
                -0.5f, -0.5f, 0.0f,
                 0.5f, -0.5f, 0.0f,
                 0.5f,  0.5f, 0.0f,
        };

        int[] indices = new int[]{

                0, 1, 3, 3, 1, 2

        };

        Vertex vertex = loader.loadToVAO(positions, indices);

        while(isRunning) {

            update();
            renderer.prepare();
            renderer.render(vertex);

            if(glfwWindowShouldClose(display.window)) {
                isRunning = false;
            }
        }

        renderer.clear();
    }

    public void update() {

        if(KeyboardInput.isKeyDown(GLFW_KEY_ESCAPE)) {
            isRunning = false;
        }

        glfwSwapBuffers(display.window);
        glfwPollEvents();
    }
}

Display Where i call createCapabilities method
package ms.main;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;

import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWVidMode;

import ms.input.KeyboardInput;

public class Display {

    @SuppressWarnings("unused")
    private GLFWKeyCallback keyCallback;

    private int width;
    private int height;

    private String title;

    public long window;

    public Display() {

    }

    public Display(int width, int height, String title) {

        this.width = width;
        this.height = height;
        this.title = title;
    }

    public void init() {

        glfwInit();

        if(!glfwInit()) {
            System.err.println("Failed to initialize GLFW");
        }

        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
        glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

        window = glfwCreateWindow(width, height, title, NULL, NULL);

        if(window == NULL) {
            System.err.println("Failed to create Window");
        }

        keyCallback = glfwSetKeyCallback(window, keyCallback = new KeyboardInput());

        GLFWVidMode vidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());

        glfwSetWindowPos(window,
                        (vidMode.width() - width) / 2,
                        (vidMode.height() - height) / 2);

        glfwMakeContextCurrent(window);
        glfwSwapInterval(1);
        glfwShowWindow(window);

        createCapabilities();
    }

    public void libVersion() {

        System.out.println("LWJGL Version: " + glfwGetVersionString());
        System.out.println("OpenGL Version: " + glGetString(GL_VERSION));
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

The problem I think is in the createCapabilities() method position but I do not know how to solve.
State that I am a beginner and I'm getting closer now to the creation of video games.
Thanks in advance for any solutions.


text:
Q: Crash - EXC_BREAKPOINT(CODE=1) while posting the notification How to fix the

Thread 1 EXC_BREAKPOINT(code=0,subcode=0x18e0173f4)

When I'm posting a changeLoggingState Notification,
Code screenshot
Crash screenshot

A: Did you set to nil in selector?
[NSNotificationCenter.defaultCenter addObserver:self
                                     selector:nil
                                         name:notificationName
                                       object:nil];

This maybe make this happen.


text:
Q: Move a popup window using setInterval() in javascript I'm trying to make a window pops up and then moves continuously using setInterval(). It pops up but it doesn't move.
I'm using all the html files in the same directory.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>popup</title>
  </head>
  <body>

    <input type="button" name="" value="new window" onclick="newWin();">
    <input type="button" name="" value="stop window" onclick="stopWin()">

    <script type="text/javascript">
    var win1;
    var interv;

    function moveWin(){
      win1.moveBy(100, 100);
      win1.focus();
    }

    function newWin(){
      win1 = window.open('new.html', 'win1', 'width=200, height=150');
      win1.focus();
      interv = setInterval(moveWin, 1000);
    }

    function stopWin(){
      clearInterval(interv);
    }

    </script>
  </body>
</html>


text:
Q: Unable to save or update postmeta for custom post type via action using save_post hook I'm trying to update a custom field by hooking into the save-post action, but for reasons I can't figure out, it's not working.
The following function is placed in the theme's functions.php:
function save_address_meta() {

      $meta = get_post_meta( get_the_ID() );

      $address = $meta['address'];
      update_post_meta(get_the_ID(), $address, 'test');
}
add_action( 'save_post', 'save_address_meta', 50 );

I've tried using pre_post_update as well, as I understand that save_post won't actually fire unless something, other than a custom field, is updated in the post - but no luck with this one either.
I've spent a few hours searching for solutions on stackexchange and various other sources online, but just not coming right. This is a dumbed-down version of the original code, but even in this basic state it doesn't appear to be working.
Basically, I'm trying to get the custom field in question, then update it with a string value.
If I print_r the $meta array, the custom field value appears in an array as follows:
 [address] => Array ( [0] => 50 Call Lane Leeds LS1 6DT United Kingdom )

I've also tried accessing this custom field in the function above using $address = $meta['address'][0].
I can echo out the value of the key this way, but if I'm not mistaken, it's the key I'll need to reference in order for the string, in the 3rd argument, to update the value as intended.

A: The save_post hook will fire whenever WordPress saves a post to the database. This includes saving WP revisions which will have a different post ID than the actual post. It's more than likely you are getting and saving the post meta to a revision instead of to the actual post.
Also, the save_post hook passes a few variables when it fires, including the post ID, so you don't have to use the get_the_ID() function.
function wpse_261414_save_post( $post_id, $post, $update ) {
  //* Make sure this isn't a post revision
  if( wp_is_post_revision( $post_id ) ) {
    return;
  }
  $meta = get_post_meta( $post_id );
  $address = $meta[ 'address' ];
  update_post_meta( $post_id, $address, 'test' );
}
add_action( 'save_post', 'wpse_261414_save_post', 10, 3 );

A: Try changing update_post_meta(get_the_ID(), $address, 'test'); to update_post_meta(get_the_ID(), 'address', 'test');

A: Why don't you try something like this;
function save_address_meta() {
    global $post;
    if($post->post_type == 'your-custom-post-type'){
        $address_field = 'test'; //Get your address field here
        update_post_meta($post->ID, 'address', 'test');
    }
}
add_action( 'save_post', 'save_address_meta' );

And you can get your field value elsewhere may be for example inside the loop as;
$address = get_post_meta($post->ID, 'address', true);

A: I had these symptoms, but it turned out to be a validation check behaving unexpectedly, namely:
if( !current_user_can( 'edit_post') ) return;

This had been working (for several years), but a Wordpress update caused it to fail.
I amended it to also take the $post_id (as per the documentation example here):
if( !current_user_can( 'edit_post', $post_id) ) return;

and all was well. So in case this helps anyone else...


text:
Q: Room Library - relationship between tables having auto generated keys The examples I came across were forming relations without primary key, my database schema is as follow.
I have primary key in both tables, and I'm attempting to create a DAO method that will join both user and department tables to display a record.
Question, how to create a DAO method to access the record joined by the department information. I prefer to do without creating more data classes if possible. for instance using Map<User, Department>. If there's none then I will accept other solutions.
User Table
+----+----------+----------+---------------+
| id | username |   name   | department_id |
+----+----------+----------+---------------+
|  1 | johndoe  | John Doe |             3 |
|  2 | janedoe  | Jane Doe |             4 |
+----+----------+----------+---------------+

User data class
@Entity(tableName = "user")
data class User(
    @PrimaryKey (autoGenerate = true) var id: Long,
    var username: String,
    var name: String,
    var department_id: Long)

Department Table
+----+----------------+
| id |      name      |
+----+----------------+
|  1 | Sales          |
|  2 | Account        |
|  3 | Human Resource |
|  4 | Marketing      |
+----+----------------+

Department data class
@Entity(tableName = "department")
data class Department(
    @PrimaryKey(autoGenerate = true) var id: Long,
    var name: String)

My attempt at DAO
@Dao
interface UserDAO {

    @Query("SELECT user.*, department.name AS 'department_name' FROM user " +
            "INNER JOIN department ON user.department_id = department.id " +
            "WHERE user.id = :id")
    fun findById(id: Long): Map<User, Department>
}

Edit
Will it work if Department is composed inside User? If that's the case then how the query inside DAO would look like?
@Entity(tableName = "user")
data class User(
    @PrimaryKey (autoGenerate = true) var id: Long,
    var username: String,
    var name: String,
    @Embedded var department: Department)

data class Department(
    @PrimaryKey(autoGenerate = true)
    var id: Long,
    var name: String? = null): Parcelable

DAO attempt
@Query("SELECT * FROM user " +
    "INNER JOIN department d ON department.id = d.id " +
    "WHERE id = :id")
fun findById(id: Long): Map<User, Department>

A: Your code works as it is BUT due to ambiguous column names (id and name) values are not as expected.
Here's the result (noting that User id's are 500 and 501 instead of 1 and 2 to better highlight the issue) when debugging, with a breakpoint at a suitable place and when using:-
findById(500)

then the debugger shows :-

That is that although John's department id is 3, it is instead 500 in the Department itself, likewise the name of the department is John Doe not the expected *Human Resource.
This is because Room doesn't know which id is for what and likewise name.
The fix is to use unique column names. e.g. with:-
@Entity(tableName = "department")
data class Department(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "dept_id")
    var id: Long,
    @ColumnInfo(name = "dept_name")
    var name: String
 )

*

*i.e. the columns in the table, but not in the Department have been changed. You could just change the name of the fields to be unique names.

Obviously if the column names are changed then the SQL has to be changed accordingly, so :-
@Query("SELECT * FROM user " +
        "INNER JOIN department ON department_Id = dept_id " +
        "WHERE id = :id")
fun findById(id: Long): Map<User, Department>

*

*as the column names now have no ambiguities then there is no need to use table names to differentiate (you still can. Without the table banes the SQL can be more concise.

Now Debug shows:-

Additional re Edit

Will it work if Department is composed inside User?

If you use @Embedded within an @Entity annotated class that is included in the entities parameter of the @Database annotated class then the resultant table has columns as per the embedded class.
If the embedded class was previously a table then in respect of the relationship that doesn't exist and that previous table may well be defunct.
There is an issue with the embedded Department in that you will have 2 columns named id
From a database perspective, if what was a 1 to many relationship then the same data (e.g. Human Resource) will be repeated and is contrary to normalisation.
In regard to the query
@Query("SELECT * FROM user " +
    "INNER JOIN department d ON department.id = d.id " +
    "WHERE id = :id")
fun findById(id: Long): Map<User, Department>

Then this will not work as there will be no department table (as according to your code the Department class is not annotated with @Entity).

A: Room supports this since version 2.4 as described in the official documentation. Similar issue to yours appear to be solved also in this answer https://stackoverflow.com/a/72990697/5473567
In your concrete example you are forgetting, that the relation is 1:N, therefore your return type in the DAO function should look like this Map<User, List<Department>>.
Also the department.name AS 'department_name' in your SELECT is wrong. The field name in the data class Department is called name, therefore also in Database table department this field will be called name. If you would like to change its name to the department_name as you use in your SELECT, you have to use annotation @ColumnInfo as described in here. The data class will then look like this:
@Entity(tableName = "department")
data class Department(
    @PrimaryKey(autoGenerate = true) var id: Long,
    @ColumnInfo(name = "department_name") var name: String
)

Last tip, if you are pulling full data from the database, there is enough to use SELECT * FROM..., Room will resolve it for you.
Finally the whole DAO interface may look like this:
@Dao
interface UserDAO {
    @Query("SELECT * FROM user " +
        "INNER JOIN department ON user.department_id = department.id " +
        "WHERE user.id = :id")
    fun findById(id: Long): Map<User, Department>
}

A: Solved. Based on the answers, here's my solution without using additional data classes while also keeping the column names intact, for instance using id column in each table without any prefix (preferable). I had to use user.id in the WHERE clause to avoid ambiguity
User
@Entity(tableName = "user")
data class User(
    @PrimaryKey (autoGenerate = true)
    var id: Long,
    var username: String,
    var name: String,
    var department_id: Long)

Department
@Entity(tableName = "department")
data class Department(
    @PrimaryKey(autoGenerate = true)
    var id: Long,
    var name: String)

DAO Query
@Query("SELECT * FROM user " +
        "INNER JOIN department ON user.department_id = department.id " + // fixed from user.id = department.id
        "WHERE user.id = :id")
fun find(id: Long): Map<User, Department>


text:
Q: Android: should I use MimeTypeMap.getFileExtensionFromUrl()? [bugs] For example,  I wanted to get the file Extension from the file URL using the function below:
File name:
Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg

Url of the file:
String url = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";

Function call:
String extension = MimeTypeMap.getFileExtensionFromUrl(url);

But I'm getting an exception on the function call. Is this a bug or a feature?
It works fine for file names that don't contain that many foreign characters (such as paranthesis).
Is the function buggy? Am I missing something? How am I supposed to differentiate a bug from a feature? I've read the function description and it should work properly.
Do you personally use it in your projects? It doesn't seem reliable.

A: private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

A: When I test your code, no exception is thrown for me.  Though the proper file extension "jpg" is not returned. I would not advise using MimeTypeMap. An easy way to obtain the file extension instead is as follows:
String file = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";
String exten = "";

int i = file.lastIndexOf('.');
if (i > 0) {
    exten = file.substring(i+1);
}

As to why MimeTypeMap.getFileExtensionFromUrl(url) fails? It's expecting a properly formated URL String, which yours is not.  You should first encode it using URLEncoder. For example:
String url = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg";
url = URLEncoder.encode(url, "UTF-8");

This should allow MimeTypeMap.getFileExtensionFromUrl(url) to work properly but unfortunately it still doesn't. Why? URLEncoder will change all spaces to a '+' sign and getFileExtensionFromUrl considers that an invalid character. This part, IMHO, is a bug.
From my experience, most people don't use this method. In fact, I never heard of it until you posted this question. Probably because finding a file extension is fairly trivial and most people write code similar to what I posted above.

A: I use this in my project and it works unless there certain characters in the file name,
I decided to not go the route of splitting the string myself.
I made a work around for the issue:
String ext = MimeTypeMap.getFileExtensionFromUrl(sanitizeFileName(Uri.encode(name)));

And i made this method to sanitize file names:
public static String sanitizeFileName(String name)
{
    byte[] invalidChars = new byte[]{34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47};
    for(byte i : invalidChars)
    {
        name = name.replace((char)i,'_');
    }
    return name;
}

The sanitize method is useful for other things as well.

A: Solution from the answer https://stackoverflow.com/a/72275100/9308731

String[] fileArr = arrPath[i].split("\\.");
String extention =
fileArr[fileArr.length - 1];

This works fine. I tried lastIndexOf() as given in one of below answer but that gives incorrect output in android meanwhile that works well n normal java code.


text:
Q: rake db:setup -> rake aborted! Errno::ENOENT: No such file or directory - identify Im trying to get setup on an existing ruby on rails project, but am getting hung up on the postgres db setup.  I used RVM to set up the project with ruby 2.1.2.  Installed the pg gem with homebrew using the following command:
gem install pg -- --with-pg_config=/usr/local/bin/pg_config

My database.yml file looks like this:
development:
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  username: myusername
  password:

test:
  adapter: postgresql
  encoding: unicode
  database: myapp_test
  pool: 5
  username: myusername
  password:

I bundle installed all my gems.
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.2'
gem 'activerecord-session_store'

# Use postgresql as the database for Active Record
gem 'pg'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery-ui-rails'

# authentication using Devise (email / password) and omniauth (oauth)
gem "devise", '~> 3.2.0'
gem 'devise_invitable', '~> 1.3.0'
gem "beta_invites", :github=>'danman01/beta_invites'
gem 'jquery-datatables-rails', git: 'git://github.com/rweng/jquery-datatables-rails.git'
gem "omniauth-soundcloud"
# validation for emails
gem 'valid_email'

# set env variables within config/application.yml
gem "figaro"

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
# gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

# User roles. ex: User.first.add_role!("admin")
gem "easy_roles"

# manage meta tags
gem "meta-tags", :require => "meta_tags"

# error notification. TODO - setup https://github.com/smartinez87/exception_notification
gem 'exception_notification', git: "git://github.com/smartinez87/exception_notification.git"

# nice rails urls for seo and readability
gem "friendly_id", '~> 5.0.0'

# use foreman start to startup multiple processes at once (i.e. rails and delayed job queue)
gem "foreman"

gem "nokogiri", '~> 1.6.3'

# pagination
gem "kaminari"

# admin panel, available at /admin
gem "rails_admin"

# cron scheduling for the server. See config/schedule
gem 'whenever', :require =>false

# tool to party
gem 'httparty'

gem 'simple_form'
gem 'bootstrap-sass', '~> 3.1.1'

# app permissions. set in models/ability.rb
gem 'cancancan', '~> 1.8'

# caching
gem 'dalli'

# activity feed
gem 'public_activity'

# image upload
gem 'carrierwave'
gem 'carrierwave-aws'
gem 'mini_magick'

gem "sidekiq"
gem 'sinatra', require: false
gem 'slim'
# tree structure
gem "ancestry"

# more organized db seeds
gem "seedbank"

# run code safely in migrations
gem 'migration_data'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

group :development do

  # better formatting of errors
  gem "better_errors"
  # do not output so much about assets to console
  gem "quiet_assets"
  # debugging tool: https://github.com/banister/binding_of_caller
  gem "binding_of_caller"
  gem "tracer_bullets"
end

group :development, :test do
  gem 'rspec-rails'
  gem "faker"
  gem "factory_girl_rails", "~> 4.0"
  gem "pry-rails"
  gem 'pry-byebug'
  # preload rails app to speed things up
  gem "spring"
  gem "spring-commands-rspec"
  # auto run things
  gem "guard"
  gem "guard-rspec", require: false
  gem 'rb-fsevent' if `uname` =~ /Darwin/
  gem 'thin' # or thin

end

group :development, :production do
  gem 'cohort_me'
end

group :test do
  gem 'capybara'
  gem "launchy"
  gem "database_cleaner"
end

# Rails view utilities

# use country-select with priority countries like: country_select("user", "country_name", [ "United Kingdom", "France", "Germany" ])
gem 'country-select'

# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.1.2'

# Use unicorn as the app server
gem 'unicorn'

# random comment

# Use Capistrano for deployment

gem 'capistrano-rails', '~> 1.1'
gem 'capistrano', '~>3.1'
gem 'capistrano-bundler', '~> 1.1.2'
gem 'capistrano-rvm'
gem 'capistrano-sidekiq', github: 'seuros/capistrano-sidekiq'#
# gem 'rails_12factor', group: :production
# ruby '2.1.1'
gem 'rb-fsevent'

I started the postgres server manually using:
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

The logfile outputs this:
ERROR:  database "myapp_development" already exists
STATEMENT:  CREATE DATABASE "musictown_development" ENCODING = 'unicode'
ERROR:  database "myapp_test" already exists
STATEMENT:  CREATE DATABASE "musictown_test" ENCODING = 'unicode'

Alternatively i used the postgresapp to start the server.
And when I run rake db:setup I get this:
myapp_development already exists
myapp_test already exists

It creates a bunch of tables and indexes then when it gets here it stops:
-- initialize_schema_migrations_table()
   -> 0.0154s
rake aborted!
Errno::ENOENT: No such file or directory - identify
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/subexec-0.2.3/lib/subexec.rb:71:in `spawn'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/subexec-0.2.3/lib/subexec.rb:71:in `spawn'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/subexec-0.2.3/lib/subexec.rb:55:in `run!'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/subexec-0.2.3/lib/subexec.rb:41:in `run'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:405:in `run'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:399:in `run_command'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:184:in `valid?'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:140:in `create'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:47:in `read'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:111:in `block in open'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:110:in `open'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/mini_magick-3.8.0/lib/mini_magick/image.rb:110:in `open'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/processing/mini_magick.rb:260:in `manipulate!'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/processing/mini_magick.rb:153:in `resize_to_fit'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/processing.rb:84:in `block in process!'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/processing.rb:76:in `each'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/processing.rb:76:in `process!'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/callbacks.rb:18:in `block in with_callbacks'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/callbacks.rb:18:in `each'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/callbacks.rb:18:in `with_callbacks'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/uploader/cache.rb:122:in `cache!'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/mount.rb:329:in `cache'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/mount.rb:163:in `image='
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/carrierwave-0.10.0/lib/carrierwave/orm/activerecord.rb:39:in `image='
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/attribute_assignment.rb:42:in `public_send'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/attribute_assignment.rb:42:in `_assign_attribute'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/attribute_assignment.rb:29:in `block in assign_attributes'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/attribute_assignment.rb:23:in `each'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/attribute_assignment.rb:23:in `assign_attributes'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/core.rb:460:in `init_attributes'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/core.rb:185:in `initialize'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/inheritance.rb:27:in `new'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/inheritance.rb:27:in `new'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/activerecord-4.0.2/lib/active_record/persistence.rb:36:in `create'
/Users/myusername/Documents/MusicTown/musictown/db/seeds.rb:9:in `block in define_seed_task'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/seedbank-0.3.0/lib/seedbank/dsl.rb:24:in `module_eval'
/Users/myusername/.rvm/gems/ruby-2.1.2/gems/seedbank-0.3.0/lib/seedbank/dsl.rb:24:in `block in define_seed_task'
/Users/myusername/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval'
/Users/myusername/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => db:setup => db:seed => db:seed:common => db:seed:original
(See full trace by running task with --trace)

Maybe theres something wrong with one of the gems in the gemfile?
This question is sorta similar: Carrierwave, Rails 4; Errno::ENOENT (No such file or directory - identify).  Maybe some gem is the wrong version?

A: To fix this, install ImageMagick CLI tools from here: imagemagick.org/script/binary-releases.php, Mac OS Binary Release.  Installing with MacPorts, which adds the paths to my .bash_profile file. Now rake db:setup command is able to find ImageMagick, and works.