text:
Q: MongoDB - Query an Array of Embedded Documents I recently started using MongoDB to save data from a project, the basic idea is the following.
On the server side I receive some JSON objects on a WebSocket and store it in the database.
The data I receive looks something like this:
{
    {ident: "message_1"},
    data:
    [
        {id: "data_1", value : 10},
        {id: "data_2", value : 20},
        {id: "data_3", value : 40},
        {id: "data_4", value : 60},
        {id: "data_4", value : 60},
    ],
    timestamp : 12234456
}

And I'm currently saving the entire JSON object in the database.
The server also should handle user http requests where it queries the database for the requested data. The user requests are always for one element of the  data array and the timestamp. Thus the server response should look like this:
{ id: "data_1", value : 10, timestamp : 12234456}

I tried using db.collection.find with $elemMatch but my output still contains the data array and the desired element.
{
    data:
    [{
        id: "data_1",
        value: 10
    }],
   timestamp : 12234456
}

So my question is if there's any possibility to query the database and return only the desired element of ´data´ array combined with the timestamp or I'll need re-create the response JSON object after reading the database.
Kind regards.

A: Welcome to the mongo world. You can easily achieve this with aggregations

*

*$uwnind to deconstruct the array

*$match to get the desire value

*$addFields to add new field to the object

*$replaceRoot to make the object as root

Here is the code
db.collection.aggregate([
  { "$unwind": "$data" },
  { "$match": { "data.id": "data_1" } },
  { "$addFields": { "data.timestamp": "$timestamp" } },
  { "$replaceRoot": { "newRoot": "$data" } }
])

Working Mongo playground

A: Although @varman answer is correct for the question, to better match my case where the array data will have a lot of elements (over 100), as @varman in the comment ´unwind´ can be expensive specially when the array contains loads of elements. So the ideal case I would prefer doing the ´unwind´ when the array only contains de desired element, to achieve that I changed the orders to the following:

*

*Use "$match To get only the documents with the desired data element

{ "$match": { "data.id": "data_1" } }

*

*Use $project and $filter to filter out the unwanted elements from data

   $project: {
      data: {
        $filter: {
          input: "$data",
          as: "data",
          cond: {$eq: ["$$data.id", "data_1"]}
        }
      },
      "timestamp": 1,
      "_id": 0
    }

*

*Now add the timestamp field as in the correct answer

  { $addFields: {"data.timestamp": "$timestamp"} }

*

*Use unwind to deconstructs data array field from the input documents to output a document for each element.

  {
    $unwind: "$data"
  }

*

*Then use $replaceRoot replaces the input document with the data fields.

{"$replaceRoot": {"newRoot": "$data"}}

Hope this will be usefull to anyone needing to do the same, and if you have any recommendation/improvements on my current setup please I'm in for advices as I'm new to MongoDB.
Running example Mongo Playground


text:
Q: Dynamic target names in Python doit I have a Python doit script with task that generates files. The file names change depending on task arguments.
Is there any way to include these files in the targets list?
Unfortunately task arguments do not get populated in target name strings.
'targets': ['targetfile{version}']

Example task:
def task_dynamic():
    return {
        'actions': ['touch targetfile{version}'],
        'params': [
            {
                'name': 'version',
                'short': 'v',
                'default': '0'
            }
        ],
        'targets': []
    }

Example command-line:
$ doit dynamic -v 8

A: You can dynamically modify task attributes on actions (just pass the magic parameter task), or on custom uptodate i.e.
DOIT_CONFIG = {
    'action_string_formatting': 'new',
}

def set_target(task, values):
    version = task.options.get('version', '0')
    task.targets.append(f'targetfile{version}')

def task_dynamic():
    return {
        'actions': ['touch targetfile{version}'],
        'params': [
            {
                'name': 'version',
                'short': 'v',
                'default': '0'
            }
        ],
        'uptodate': [set_target],
    }

There is a proposed change that will allow this to be achieved more easily, see issue #311

A: There is a non-ideal resolution: I put my dynamic outputs in a directory with a stable name, and then referred to that directory in my targets list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: YouTube API 2 Get All comments .net I am using youtube api 2.0 to get comments.
Currently i have this:
YouTubeRequest request = new YouTubeRequest(new YouTubeRequestSettings("Project", devKey));
Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoId);
Video video = request.Retrieve<Video>(videoEntryUrl);
var comments = request.GetComments(video);

How i can change StartIndex to get all videos?

A: Unfortunately, it is not possible to retrieve more than 100 comments per video. As YouTube won't allow it. However, by using start-index 1, you can get first 1-50 and with start-index 51, you can retrieve 51 to 100th comments


text:
Q: C3JS bar chart with specific order with color i currently working on c3 chart to draw Stack bar chart. i can able to populate the dynamic data based on click event, its work fine but when i look into chart the bar chart which displayed in charts its not positioned properly based on my inputs
Here i attach my Sample Code :
Rowvalue = [['1-10'].concat(processed_value_final0),
['11-50'].concat(processed_value_final1),
['51-200'].concat(processed_value_final2),
['201-500'].concat(processed_value_final3),
['501-1k'].concat(processed_value_final4)];
groupCol = ['1-10', '11-50', '51-200', '201-500', '501-1k'];

var chart = c3.generate({
bindto: div_id,
    data: {
        columns:Rowvalue,
        type: 'bar',
        order: 'asc',
        groups: [
            groupCol
        ]
        },
        bar: {
            width: barwd
            } ,
        grid: {
            y: {
                show: true,
                lines: [{value:0}]
            }
            },
        axis: {
            x:
            {
                type: 'category',
                categories: keyValue
            },
            y:
            {
                min : 0,
                padding : {
                bottom : 0
                }
            }
        },
    color: {
        pattern: ['#ED5565', '#23C6C8', '#F8AC59', '#1AB394', '#1C84C6', '#F8AC59', '#23C6C8', '#ED5565', '#F8AC59']
        },
    legend:
    {
    show: true,
    position:'right'
    },
    tooltip :
    {
    show:true
    }
   });

A: You need to change the value in the order section of the configuration, which can be either i) 'asc' or 'desc' - which work on data values i.e. biggest or smallest values first, ii)| null for the same (but not, see later) ordering as the data, or iii) an array of the data series keys or iv) a function that operates on the data series keys.
Here we change the order to be an array - the groupCol array but reversed:
    order: groupCol.reverse(),

This changes the order to be the reverse of the ordering defined in groupCol and rowValue variables. The reason it needs to be reversed is because the stack drawing algorithm starts from the bottom up while the legend key lists the data series keys from the top down. This is also why the null option wouldn't work, the bars and the legend would be reversed in order from each other.


text:
Q: Check if there is punctuation or number in the middle of a word For example, I'm trying to have a boolean function if a word has not only letters but also has either number or punctuation or both. If there is only punctuation that exists at the end and no number, it should return False.

*

*g3n3rator --> return True

*0ffer --> return True

*Work!ng --> return True

*morning --> return False

*hello? --> return False

*hell0? --> return True

A: For your solution, you can always use regex. As of a non-regex way, try
def check(inp):
    if inp.isalpha():
        return False
    if not any(char.isdigit() for char in inp) and inp[-1] in string.punctuation:
        return False
    return True

This outputs correct values to all the test cases given in the problem statement. Hope this helps!


text:
Q: Rectangle CornerRadius This is somewhat a general question about rectangles with border radii. I'm working with a developer that's taking my Photoshop comps and applying the designs to a prototype in Blend. They've told me that in Blend it's not possible to create a rectangle with only 2 curved corners. Supposedly you have to have all 4 corners with a border radius or none at all. Ideally I'd like only the top left and right corners with a border radius of 10 and the bottom edges without a curve. I'd just like to know if this is possible to do.

A: It is not be possible with Rectangle. But it is possible using Border.
<Border Width="230" Height="100" CornerRadius="10 10 0 0" Background="red"/>

The values will be applied in this fashion - "TopLeft TopRight BottomRight BottomLeft"

A: Using Clip : RectangleGeometry
<Rectangle Fill="Blue" HorizontalAlignment="Center"  VerticalAlignment="Center" Height="200" Width="200">
    <Rectangle.Clip>
            <RectangleGeometry Rect="0,20,200,200"  RadiusX="20" RadiusY="20"/>
    </Rectangle.Clip>
</Rectangle>

Using VisualBrush
 <Rectangle>
    <Rectangle.Fill>
        <VisualBrush Stretch="None">
            <VisualBrush.Visual>
                <Border CornerRadius="50,50,0,0"  Width="300" Height="200" Background="Navy"></Border>
            </VisualBrush.Visual>
        </VisualBrush>
    </Rectangle.Fill>
</Rectangle>


text:
Q: PHP Multidimensional Array Length This is a multidimensional PHP array.
$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);

I can find out the length of the array. That means
count($stdnt); // output is 4

[
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94)
] `

But can't get the internal array length.
How can I ?

A: The other way to count internal array lengths is to iterate through the array using foreach loop.
<?php
$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);

foreach($stdnt as $s)
{
    echo "
".count($s);
}
?>

A: please use sizeof function or count function with recursive
 e.g echo (sizeof($stdnt,1) - sizeof($stdnt)) ; // this will output you 9 as you want .

first sizeof($stdntt,1) ; // will output you 13 . count of entire array and 1 mean recursive .

A: If you are assuming the subarrays are all the same length then:
$count = count($stdnt[0]);

If you don't know the keys:
$count = count(reset($stdnt));

To get an array with a separate count of each of the subarrays:
$counts = array_map('count', $stdnt);

A: According to the hint from Meaning of Three dot (…) in PHP, the following code is what I usually use for this case:
$stdnt = array(
    array("Arafat", 12210261, 2.91),
    array("Rafat", 12210262, 2.92),
    array("Marlin", 12210263, 2.93),
    array("Aziz", 12210264, 2.94),
);
echo count(array_merge(...$stdnt));

The Splat operator "..." will only work,

*

*Only if the first level keys are in integer, ie, not "strings"

*PHP > 5.6

A:   // You may try as per this sample

  $cars=array(
    array("volvo",43,56),
    array("bmw",54,678)
  );
  $mySubSize=sizeof($cars);
  for ($i=0;$i<$mySubSize;$i++) {
    foreach ($cars[$i] as $value) {
      echo "$value
";
    }
  }


text:
Q: How to infer generic in a curried function? I'm trying to type out an API for querying collections. I want it to be used like so:
interface Car {
  model: string
  doors: 2 | 4 | 5
  designers: string[]
}

const result = query({
  model: [ contains('tesla') ],
  doors: [ is(3) ],
  designers: [ includes('Franz') ],
  take: 5,
});

So here's my imperfect approach:
type Query<Entity extends EntityType> = (config: QueryConfig<Entity>) => Promise<Entity[]>
type QueryConfig<Entity extends EntityType> =
  { [K in FilterScalarMembers<Entity>]?: ScalarBuilderFn<Entity[K]>[] }
  & { [K in FilterCollectionMembers<Entity>]?: CollectionBuilderFn<Entity[K]>[] }
  & { take: number };

type FilterCollectionMembers<Entity extends EntityType> =
  { [K in keyof Entity]: Entity[K] extends CollectionType ? K : never }[keyof Entity]

type FilterScalarMembers<Entity extends EntityType> =
  { [k in keyof Entity]: Entity[k] extends (string | number) ? k : never }[keyof Entity]

type ScalarBuilderFn<T extends string | number> = (builder: ScalarQueryBuilder<T>) => ScalarQueryBuilder<T>
type CollectionBuilderFn<T extends CollectionType> = (builder: CollectionQueryBuilder<T>) => CollectionQueryBuilder<T>
type ScalarQueryBuilder<T extends string | number> = {}
type CollectionQueryBuilder<T extends CollectionType> = {}
type EntityType = Record<string, any>
type CollectionType = ((string | number)[]) | Set<string | number>

const is = <T extends string | number>(arg: T): ScalarBuilderFn<T> => function() {} as unknown as ScalarBuilderFn<T>;

The problem becomes apparent here: doors: [ is(3) ] as the type didn't get narrowed to 2 | 4 | 5, TypeScript doesn't give out an error about the 3 argument. Can we do something to the is function to help it infer the type correctly?

A: You can do it using indexed types:
const result = query({
    doors: [is<Car['doors']>(3)]
});

You can pass is a generic parameter of Car['doors'] which will tell is that its parameter has to be assignable to Car['doors'], namely 2 | 4 | 5.
I'm not sure you need all of those types then - unless they do other things not shown here. All you need is for is to have one generic type parameter which its parameter needs to match
const is = <T>(val: T) => { } // rest of the implementation


text:
Q: Cannot call base __init__ in a class created with type() I create a class with type as I need to use a variable for the base.
It works fine if I don't provide an __init__ method, but when I do provide one, I am unable to call the base's __init__.
Works:
def constructor():
    blah blah
    api = importlib.import_module(xtype)
    mc = type('mc', (api.aclass,), {})
    obj = mv(**args)
    return obj

doesn't work, returns "SystemError: super(): __class__ cell not found"
def constructor():
    blah blah
    api = importlib.import_module(xtype)
    mc = type('mc', (api.aclass,), dict(__init__ = mc__init)
    obj = mc(**args)
    return obj

def mc_init(*args, **kwargs):
    do_some_stuff
    super().__init__(*args, **kwargs)

doesn't work, returns "Base mc.__init__ not called." later at object creation:
def constructor():
    global api
    blah blah
    api = importlib.import_module(xtype)
    mc = type('mc', (api.aclass,), dict(__init__ = mc__init)
    obj = mc(**args)
    return obj

def mc_init(*args, **kwargs):
    global api
    do_some_stuff
    api.aclass.__init__(*args, **kwargs)

x = constructor()

How can I call the init for the base class?
Thanks.

A: I'm surprised that your type calls are working; bases should be a tuple ((api.aclass,)).  Is this just a typo?
Your super() call in (2) won't work as it is outside a class declaration; Python 3 super magic is quite complicated and to be honest a little fragile.  You could write super(mc, self).__init__(*args, **kwargs).
However, there's no reason for you not to use a proper class declaration here (especially if you don't understand how to use 3-argument type); Python is perfectly OK with classes being declared with variable bases:
def constructor():
    ...
    api = importlib.import_module(xtype)
    class mc(api.aclass):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    obj = mc(**args)
    return obj


text:
Q: How to get particular Value by Key from JSON request by using Java Reflection Formatted JSON Data
{
 "userId":"123",
 "userName":"user",
 "age":12
}

From Above JSON request I want to fetch only userName data to store in database by using Java Reflection.

A: You can use a JSON library to parse the string and retrieve the value.
Basic Example:
import org.json.JSONObject;

public class Main {

    public static void main(String[] args) {
        String jsonString = "{ \"userId\":\"123\", \"userName\":\"user\", \"age\":12 }";
        JSONObject jsonObject = new JSONObject(jsonString);
        String userName = jsonObject.getString("userName");
        System.out.println("UserName is: " + userName);
    }

}

Output:
UserName is: user

Note: Don't forget to add json dependency in POM file.
<dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
</dependency>

Although more JSON libraries are available such as jackson, google-gson and many more. You can use any of them.

A: You can use the jackson json parser.
Below is just a code sample(no guarantee that it will compile and work for you) you should put into your controler method receiving the request.
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.ObjectWriter;

    //put below codes in your request handling method
    String jsonStr = req.getReader().lines().collect(Collectors.joining(
                        System.lineSeparator()));
    System.out.println(jsonStr);
    JsonNode rootNode = new ObjectMapper().readTree(new StringReader(jsonStr));
    JsonNode userName=rootNode.get("userName");
    String userNameStr=userName.asText();
    // store in data base

You can refer to https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/package-summary.html for api details.

A: You can use below code to obtain username from your json data.
JSONObject obj = new JSONObject(YOUR_JSON.toString());
String userName = obj.getString("userName");

A: There are 2 solutions:

*

*Simplest: Apply a json parser such as: jackson, gson, json.org... And get username from JsonNode.

*If your requirement is just get Username, you can use regex to retrieve it
"userName":"((\\"|[^"])+)"
group(1) is your user.


text:
Q: "Renders with edge antialiasing" Makes UIViews look worse with transform I have some UIViews which have a transform with both translation and rotation and they were looking aliased so I turned on "Renders with edge antialiasing" in -Info.plist and it actually makes it look worse!
Instead of just being jaggy, they also seem to have black mixed in to the jaggy edges. There is a shadow, but the layer behind it is not black.
Is there something I'm missing here?

A: I found a lot of different advice on this, but it seems that "Renders with edge antialiasing" doesn't do a lot in the grand scheme of things. However, it helps a little extra with the solution I found below:
self.layer.shouldRasterize = YES;
self.layer.rasterizationScale = [[UIScreen mainScreen] scale];

These 2 lines go on my UIView that gets transformed which is just a layer with [UIColor clearColor] as the background. Anything with colors or images or any content is a subview. Otherwise, with the rounded corners I'm using, I saw a little black on the edges.


text:
Q: Convert MySQL table from vertical to horizontal based on id column I have a table like below
id | main_id       | image
1  | 10            | 52343.jpg
2  | 10            | 52344.jpg
3  | 10            | 52345.jpg
4  | 11            | 52346.jpg
5  | 11            | 52347.jpg
6  | 11            | 52348.jpg
7  | 11            | 52349.jpg
8  | 12            | 52350.jpg
9  | 12            | 52351.jpg

i want output like this :
id | main_id  | image1
1  | 10       | 52343.jpg, 52344.jpg, 52345.jpg
2  | 11       | 52346.jpg, 52347.jpg, 52348.jpg, 52349.jpg
3  | 12       | 52350.jpg, 52351.jpg

Just all images with same main_id to be in one row.

A: use group_concat()
select main_id,group_concat(image)
from tablename
group by main_id


text:
Q: java.lang.ClassNotFoundException: org.activiti.engine.test.ActivitiRule I tried creating a JUnit test for a Activiti BPMN xml (right clicking and generating it). When I run the JUnit test am getting below exception. The class which is stated as not found is in activiti-engine-5.14.jar I tried searching and found a suggestion to use JUnit 4.11. I already use that as stated in the pom.xml below. Am new to activiti, please do let me know if anything needs to be changed to avoid below exception.
JUnit test class:
package org.activiti.designer.test;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;
import java.io.FileInputStream;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.test.ActivitiRule;
import org.junit.Rule;
import org.junit.Test;

public class TestSimpleLeaveProcess {

    private String filename = "C:/Users/arun.bc/activitiws/activiti-sample/src/main/resources/diagrams/SimpleLeaveProcess.bpmn";

    @Rule
    public ActivitiRule activitiRule = new ActivitiRule();

    @Test
    public void startProcess() throws Exception {
        RepositoryService repositoryService = activitiRule
                .getRepositoryService();
        repositoryService
                .createDeployment()
                .addInputStream("SimpleLeaveProcess.bpmn.xml",
                        new FileInputStream(filename)).deploy();
        RuntimeService runtimeService = activitiRule.getRuntimeService();
        Map<String, Object> variableMap = new HashMap<String, Object>();
        variableMap.put("Empname", "Activiti");
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey("leaveProcess", variableMap);
        assertNotNull(processInstance.getId());
        System.out.println("id " + processInstance.getId() + " "
                + processInstance.getProcessDefinitionId());
    }
}

Maven test logs
-------------------------------------------------------------------------------
Test set: org.activiti.designer.test.TestSimpleLeaveProcess
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec <<< FAILURE!
initializationError(org.activiti.designer.test.TestSimpleLeaveProcess)  Time elapsed: 0 sec  <<< ERROR!
java.lang.NoClassDefFoundError: Lorg/activiti/engine/test/ActivitiRule;
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Class.java:2317)
    at java.lang.Class.getDeclaredFields(Class.java:1762)
    at org.junit.runners.model.TestClass.<init>(TestClass.java:49)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:75)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.ClassNotFoundException: org.activiti.engine.test.ActivitiRule
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 23 more

BPMN XML File
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
  <process id="myProcess" name="My process" isExecutable="true">
    <startEvent id="startevent1" name="Start">
      <extensionElements>
        <activiti:formProperty id="Empname" name="Empname" type="string"></activiti:formProperty>
      </extensionElements>
    </startEvent>
    <scriptTask id="scripttask1" name="Script Task" scriptFormat="groovy" activiti:autoStoreVariables="false">
      <script>out:println"ApplyforLeaveby"+Empname;</script>
    </scriptTask>
    <sequenceFlow id="flow1" sourceRef="startevent1" targetRef="scripttask1"></sequenceFlow>
    <userTask id="usertask1" name="H.R Approval" activiti:assignee="kermit"></userTask>
    <sequenceFlow id="flow2" sourceRef="scripttask1" targetRef="usertask1"></sequenceFlow>
    <endEvent id="endevent1" name="End"></endEvent>
    <sequenceFlow id="flow3" sourceRef="usertask1" targetRef="endevent1"></sequenceFlow>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_myProcess">
    <bpmndi:BPMNPlane bpmnElement="myProcess" id="BPMNPlane_myProcess">
      <bpmndi:BPMNShape bpmnElement="startevent1" id="BPMNShape_startevent1">
        <omgdc:Bounds height="35.0" width="35.0" x="80.0" y="150.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="scripttask1" id="BPMNShape_scripttask1">
        <omgdc:Bounds height="55.0" width="105.0" x="160.0" y="140.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="usertask1" id="BPMNShape_usertask1">
        <omgdc:Bounds height="55.0" width="105.0" x="310.0" y="140.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="endevent1" id="BPMNShape_endevent1">
        <omgdc:Bounds height="35.0" width="35.0" x="460.0" y="150.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNEdge bpmnElement="flow1" id="BPMNEdge_flow1">
        <omgdi:waypoint x="115.0" y="167.0"></omgdi:waypoint>
        <omgdi:waypoint x="160.0" y="167.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow2" id="BPMNEdge_flow2">
        <omgdi:waypoint x="265.0" y="167.0"></omgdi:waypoint>
        <omgdi:waypoint x="310.0" y="167.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
      <bpmndi:BPMNEdge bpmnElement="flow3" id="BPMNEdge_flow3">
        <omgdi:waypoint x="415.0" y="167.0"></omgdi:waypoint>
        <omgdi:waypoint x="460.0" y="167.0"></omgdi:waypoint>
      </bpmndi:BPMNEdge>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</definitions>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>sanjus</groupId>
    <artifactId>activiti-sample</artifactId>
    <version>1.0</version>
    <name>activiti-sample</name>
    <description>activiti-sample</description>
    <properties>
        <activiti-version>5.14</activiti-version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-engine</artifactId>
            <version>${activiti-version}</version>
        </dependency>
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-spring</artifactId>
            <version>${activiti-version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.168</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <inherited>true</inherited>
                <configuration>
                    <classpathContainers>
                        <classpathContainer>org.eclipse.jdt.USER_LIBRARY/Activiti Designer
                            Extensions</classpathContainer>
                    </classpathContainers>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

A: I was able to solve the NoClassDefFoundError (java.lang.NoClassDefFoundError: Lorg/activiti/engine/test/ActivitiRule) stated above by replacing Activiti version 5.14 with 5.17.0 in the pom.xml.
  <properties>
    <activiti-version>5.17.0</activiti-version>
  </properties>


text:
Q: Logback: how to log only errors to file I've been reading the logback manual for 2 hours and still can't figure how to do what I need.
It is as simple as the title says: I want to log only the errors to a file, and the other levels (including ERROR) to console.
This is the root section of my logcat.xml file:
    <root level="TRACE" >
        <appender-ref ref="CONSOLE_APPENDER" />
        <appender-ref ref="FILE_APPENDER" />
    </root>

The problem with this configuration is that it logs every level >= TRACE to both appenders.
I could let the root with only console, and define a file logger:
    <logger name='file_logger' level='ERROR' >
        <appender-ref ref="FILE_APPENDER" />
    </logger>

But then I'd have to call the normal logger like this:
LoggerFactory.getLogger(ClientClass.class);

And the file logger like this:
LoggerFactory.getLogger("file_logger");

I don't wan't to choose the logger for each class. I just want to get the root logger from the factory using the class as parameter, and have it do the correct thing depending on the level.
Is this possible?

A: I don't understand why wrong answer here is upvoted.
The guy wants ONLY error messages in his file.
Here is the correct answer:
<filter class="ch.qos.logback.classic.filter.LevelFilter">
  <level>ERROR</level>
  <onMatch>ACCEPT</onMatch>
  <onMismatch>DENY</onMismatch>
</filter>

Reference:
https://logback.qos.ch/manual/filters.html#levelFilter

A: Put this into your file appender definition:
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
    <level>ERROR</level>
</filter>

The ThresholdFilter is in logback-classic.jar.

A: Refer below code:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>


text:
Q: jQuery attribute disable not working I'm try to disable (and remove) some attributes in jQuery, but it seems not working when value is changed and set to "disabled" some fields. This script runs when a value of drop-down box is changed.
Here code below:
$(".tipo_frete").change(function(){
    if($(this).val()  == "FOB" ){
        $(".id_transp").attr("disabled");
        $(".id_transp").val("");
        $(".nome_transp").attr("disabled");
        $(".nome_transp").val("");
        $(".valor_frete").attr("disabled");
        $(".valor_frete").val("");
    }else{
        $(".id_transp").removeAttr("disabled");
        $(".valor_frete").removeAttr("disabled");
        $(".nome_transp").removeAttr("disabled");
    }
});

Did I do something wrong here?

A: use prop()
disable
$(".id_transp").prop("disabled",true);

enable
$(".id_transp").prop("disabled",false);

NOTE :  $(".id_transp").attr("disabled"); you have to pass 2 arguments like $(".id_transp").attr("disabled",true)
simplify your code
$(".tipo_frete").change(function () {
    if ($(this).val() == "FOB") {
        $(".id_transp,.nome_transp,.valor_frete").val("").prop("disabled", true);
    } else {
        $(".id_transp,.nome_transp,.valor_frete").prop("disabled", false);
    }
});

A: Yes, you are missing another parameter in attr() property.
Try this:
$(".tipo_frete").change(function(){
    if($(this).val()  == "FOB" ){
        $(".id_transp").attr("disabled","disabled");
        $(".id_transp").val("");
        $(".nome_transp").attr("disabled","disabled");
        $(".nome_transp").val("");
        $(".valor_frete").attr("disabled","disabled");
        $(".valor_frete").val("");
    }else{
        $(".id_transp").removeAttr("disabled");
        $(".valor_frete").removeAttr("disabled");
        $(".nome_transp").removeAttr("disabled");
    }
});

But when you remove those attibutes, you keep only one parameter inside and it will be removed.

A: In jQuery when you want to get attribute value, must be use .attr('key') or .prop('key') with one argument, But when you want to set a value to an attribute, you must set two arguments like as .attr('key', 'value') or .prop('key', 'value')
$(".id_transp").attr("disabled", "disabled");

//OR

$(".id_transp").prop("disabled", true);

A: element equal to selector '.id_transp';
  var $element = $(...);
        $element.prop('disabled', true);
        $element.attr('disabled', true);

        // The following do not require jQuery
        $element.get(0).disabled = true;
        $element.get(0).setAttribute('disabled', true);
        $element[0].disabled = true;
        $element[0].setAttribute('disabled', true);


text:
Q: Android current location is returned null I use LocationClient to get current location and if it fails then use LocationManager.
Some times I don't get current location of device. If it is getting location of device then it keeps getting every time I try and, if it is not able to get location and no matter how many times I try, it never gives the location. Also at the same time if I run code on multiple devices it gives location of some devices but not able to get for rest of the devices.
@Override
public void onConnected(Bundle connectionHint) {

    Location loc = locationClient.getLastLocation();
    Log.e(TAG, "location using client = " + loc.getLatitude() + ","
                + loc.getLongitude());

    // If location is not null
    if (loc != null && loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
        // code
    } else {
        // Use location manager to get location
        getCurrentLocationUsingLocationManager();
    }
}

private void getCurrentLocationUsingLocationManager() {
    // Get last known location
    Location location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // If last known location is recent then use it, otherwise request for
    // location update.
    if (location != null
            && location.getTime() > Calendar.getInstance()
                    .getTimeInMillis()
                    - THRESHOLD_ON_LAST_KNOWN_LOCATION_TIME * 1000)
    {

        // code

    } else
    {

        LocationListener locationListener = getLocationListener();

        // If Network provider is enabled, then start listening for location
        // updates
        if (locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        {

            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListener);

        }

        // If GPS provider is enabled, then start listening for location
        // updates
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
        {

            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        }

        // If none of the location providers is enabled
        if (!locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                && !locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER))
        {

            Log.d(TAG, "GPS and Network providers are disabled.");
        }
    }
}

// Initializes LocationListener to listen for location updates and return an
// instance of it.
private LocationListener getLocationListener()
{
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {

            // If location is not null and its accuracy requirement is
            // satisfied then,
            if (location != null
                    && location.getAccuracy() <= LOCATION_ACCURACY)
            {

                Log.d(TAG, "Location : " + location.getLatitude() + ", "
                        + location.getLongitude());

                locationManager.removeUpdates(this);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras)
        {

        }

        @Override
        public void onProviderEnabled(String provider)
        {

        }

        @Override
        public void onProviderDisabled(String provider)
        {

        }
    };

    return locationListener;
}


text:
Q: ASP.NET user control list/collection/array property I created user control. It has string[] public property (it may be List<string> or whatever). I want to support defining this property in aspx code, when declaring the instance of this usercontrol. Something like this:
<uc1:MyControl ID="MyControl1" runat="server">
    <MyStringCollectionProperty>
        <string>My String 1</string>
        <string>My String 2</string>
        <string>My String 3</string>
    </MyStringCollectionProperty>
</uc1:MyControl>

How to make it work?  Thanks...

A: You can actually use TypeConverterAttribute to specify a converter class (StringArrayConverter in this case).

A: As far as I know you cannot do what you want to do with a user control.  You would need to write a custom control.
See Server Control Properties Example on MSDN.

A: Here is an example of how to accomplish what you are asking for.  Child controls are read in as HTMLGeneric Controls, so you have to convert them.  As they are read in, I convert them into my custom "StringControl" class.  If you want to use a more advanced structure you can just enhance the constructor for the stringcontrol.
Partial Class UserControlStrings_MyControl
    Inherits System.Web.UI.UserControl

    Private _MyStringCollectionProperty As New MyUserControlStringCollectionClass(Me)

    <PersistenceMode(PersistenceMode.InnerProperty)>
    Public ReadOnly Property MyStringCollectionProperty As MyUserControlStringCollectionClass
        Get
            Return _MyStringCollectionProperty
        End Get
    End Property
End Class

Public Class MyUserControlStringCollectionClass
    Inherits ControlCollection

    Sub New(ByVal owner As Control)
        MyBase.New(owner)
    End Sub

    Public Overrides Sub Add(ByVal child As System.Web.UI.Control)
        MyBase.Add(New StringControl(child))
    End Sub
End Class

Public Class StringControl
    Inherits HtmlGenericControl

    Sub New(ByVal GenericControl As HtmlGenericControl)
        MyBase.New()
        Me.Value = GenericControl.InnerHtml
    End Sub

    Public Property Value As String = String.Empty

    Public Overrides Function ToString() As String
        Return Value
    End Function
End Class

You can then look in the "MyControl1.MyStringCollectionProperty" for all the values.

A: By entering your variable values in the mark-up explicitly, per your example, you are directly combining your UI with your logic.
If these values don't ever change, then there is no point to putting them in the mark-up -- it would be better to put them into your user-control's code.
If these values could be different each time the user control loads, then they ought to come from a dynamic source, such as session state variables, public variables, control values, etc.  (In that case, your user control would look them up each time it loads.)
If these values change only at design time, you could still set them onload as above, but you might consider looking at building a 'custom control' in that case.
Anyway, not sure exactly what you're trying to achieve, so hope one of these options can help.
Good luck

A: Custom User Control and Friendly Property Item Collection (Like ListBox and ListItems, but with List<Class>) on .ASPX
you can use a Collection and also List.
be sure to check http://msdn.microsoft.com/en-us/library/9txe1d4x%28v=vs.100%29.aspx - it applies very good to user control and on the stackoverflow link above i explained how you can link in the aspx page or webconfig


text:
Q: JUnit test of a method using ArrayList gets a String error This is the error trace I get:
java.lang.AssertionError: expected: java.lang.String<[{Song: title=Always artist=Blink 182}]> but was: java.util.ArrayList<[{Song: title=Always artist=Blink 182}]>

when I try and run this piece of code in the test case
assertEquals("[{Song: title=Always artist=Blink 182}]", p.getSongList());

p.getSongList is a method that returns and ArrayList<Song>. I've only added the one song so far but I am confused about how to change the expected output to java.util.ArrayList instead of java.lang.String. Any help would be greatly appreciated.

A: You are comparing an ArrayList instance with the string representation of the desired output (i.e., the String you'd get if you run toString() on the output). Instead, you should just construct the actual output you're expecting.
Your question doesn't supply the code for your Song class, so I'm guessing it's just a POJO:
Song expectedSong = new Song();
expectedSong.setTitle("Always");
expectedSong.setArtist("Blink 182");
ArrayList<Song> expectedList = new ArrayList<>(1);
expectedList.add(song);
assertEquals(expectedList, p.getSongList());


text:
Q: Where can metafont be obtained? Where is the source code or executable for Knuth's metafont program? I cannot find it anywhere!

A: The binary should be part of your TeX distribution; its name is mf.  The source is available at: CTAN

A: To be even more specific, it is here, in the file called "mf.web".  It is 23k lines of pascal mixed with heavy documentation that is something like DOXYGEN from the 70's.
If you're running a debian-based distribution the source is also in the "texlive-bin" source package in the "/texk/web2c/mf.web" subdirectory.


text:
Q: Export on nodejs alpine docker image is not accepted I want to add a http_proxy environment variable to the nodejs alpine docker image.
The Dockerfile looks like this
FROM node:6-alpine

RUN export
RUN export https_proxy='http://myproxy:8080'
RUN export http_proxy='http://myproxy:8080'
RUN export

The output when running
docker build -t myimage:latest .

looks like this
 Step 1/5 : FROM node:6-alpine
 ---> 66cf88e4fc20
 Step 2/5 : RUN export
  ---> Running in 61f5bda7989d
 export HOME='/root'
 export HOSTNAME='26ba10d264c2'
 export NODE_VERSION='6.9.5'
 export NPM_CONFIG_LOGLEVEL='info'
 export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
 export PWD='/'
 export SHLVL='1'
  ---> f04aeb89f7d0
 Removing intermediate container 61f5bda7989d
 Step 3/5 : RUN export https_proxy='http://myproxy:8080'
  ---> Running in 895d13321da8
  ---> 6a8aaa9639a9
 Removing intermediate container 895d13321da8
 Step 4/5 : RUN export http_proxy='http://myproxy:8080'
  ---> Running in 19910745f212
  ---> 1de5b4fb2b2e
 Removing intermediate container 19910745f212
 Step 5/5 : RUN export
  ---> Running in e5d186b66385
 export HOME='/root'
 export HOSTNAME='26ba10d264c2'
 export NODE_VERSION='6.9.5'
 export NPM_CONFIG_LOGLEVEL='info'
 export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
 export PWD='/'
 export SHLVL='1'
  ---> 0aa0f97555bf
 Removing intermediate container e5d186b66385
 Successfully built 0aa0f97555bf

As you can see the export on the shell is not done!
When I open a shell in the newly build image and execute the commands manually it works.
> docker run myimage:latest sh
/ # export https_proxy='http://myproxy:8080'
/ # export http_proxy='http://myproxy:8080'
/ # export
export HOME='/root'
export HOSTNAME='a759e3d30481'
export NODE_VERSION='6.9.5'
export NPM_CONFIG_LOGLEVEL='info'
export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
export PWD='/'
export SHLVL='1'
export TERM='xterm'
export http_proxy='http://myproxy:8080'
export https_proxy='http://myproxy:8080'

So what am I doing wrong?

A: This is not the correct way to define ENV variable in a Dockerfile, better use ENV see the doc https://docs.docker.com/engine/reference/builder/#/env
and by the way, group your RUN, see the doc explaining it
https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/


text:
Q: Finding elements of the principal ideal $(10)$. Let $R=2\mathbb{Z}$ be a commutative ring that does not contain $1$. What elements of $(10)$ are not in $10R$?
$R=2\mathbb{Z}=\{0,\pm 2,\pm4,\dots\}$
So, $10R=\{0,\pm 20,\pm40,\dots\}$
So am I looking for an element in the principal ideal $10$ that does not have an identity? Sorry, need some help clarifying what the question is asking. Been stumped on this problem.

A: $(10)$ is the smallest ideal or $R$ which contains $10$, therefore (recall that ideals are additive subgroups) $$(10)=\{0,\pm10,\pm20,\pm30\cdots\}$$
Assuming that the definition is $aR=\{ak\,:\, k\in R\}$, then $$10R=\{0,\pm20,\pm40,\pm60,\cdots\}$$

A: In $\Bbb Z$,
$(10) = 10\Bbb Z = \{\ldots, -30,  -20, -10, 0, 10, 20, 30, \ldots \} = \{10z, \; z \in \Bbb Z \}; \tag 1$
that is, $(10) \subset \Bbb Z$ is the set of all integer multiples of $10$; in particular, it contains the odd multiples of $10$, which are absent from $10(2\Bbb Z) = 10R \subset R$.


text:
Q: how to load a source at start in vimrc I was not able to get snipMate to work with gvim and then found that there is an existing issue.  the solution seems to be to run the following command after opening vim
 source ~/.vim/after/plugin/snipMate.vim
To save me from the pain of remembering to run that every time I open vim, I tried adding that same command to my startup settings (~/.vimrc)..however that does not seem to work.
Is there another way to load this at the time when I start vim?

A: Add this in your .vimrc:
:so ~/.vim/after/plugin/snipMate.vim

A: Set the appropriate file type without the defined type snipmate not know how to complete eg.
:set ft=python


text:
Q: Best way to optimize DB inserts using Java The program is written in java. 25 threads are processing 1 million tasks. Each task saves data into DB hence 1 million times DB insert happens. In order to optimize this, We tried following approach

*

*Tasks save data into ConcurrentLinkedDeque

*A thread polls the duque in periodic interval and gets all the available objects at that point in time.

*Once the available objects' count reaches a threshold ( say 100K ), then create a thread to save.

But this approach is not improving overall performance.
I would like to reduce the number of times (1 million times currently ) DB insert happens to improve performance. Are there any alternate solution like High Performing -  multiple concurrent publisher and single concurrent subscriber kind of implementation ?

A: Reduce the overhead of row-by-row processing by batching commands. Many APIs include ways to batch commands, or you can combine them yourself with a statement like this:
INSERT INTO products (product_no, name, price)
SELECT 1, 'Cheese', 9.99 FROM dual UNION ALL
SELECT 2, 'Bread' , 1.99 FROM dual UNION ALL
SELECT 3, 'Milk'  , 2.99 FROM dual;


text:
Q: Can't get Windows Overlay icons to work in TListView Using Borland C++ Builder 2009 I can display overlay icons in a TListView object, using my own TImageList.
However I also need this to work with the Windows icons.  Showing those icons is not a problem, but I can't get Overlay icons to work (yet).
Here's what I do (not complete and code lifted out of a bigger project, but it should illustrate the question properly) :
During Init:
SHFILEINFO info ;
SmallSystemIconsList->Handle = SHGetFileInfo( L"",
                                            0,
                                            &info,
                                            sizeof(info),
                                            SHGFI_ICON |
                                            SHGFI_SMALLICON |
                                            SHGFI_SYSICONINDEX |
                                            SHGFI_OVERLAYINDEX
                                            ) ;
DestroyIcon(info.hIcon) ;`

Everytime I want to know the index of an icon:
SHFILEINFO info ;
SHGetFileInfo(             MyFileName.c_str(),
                            FILE_ATTRIBUTE_NORMAL,
                            &info,
                            sizeof(SHFILEINFO) ,
                            SHGFI_ICON |
                            SHGFI_USEFILEATTRIBUTES |
                            SHGFI_OVERLAYINDEX
                            ) ;
DestroyIcon(info.hIcon) ;

// TListItem *ListItem
ListItem->ImageIndex    = (info.iIcon & 0x00FFFFFF) ;
ListItem->OverlayIndex  = (info.iIcon >> 24) - 1;

I notice that the proper values are being passed during testing.  For instance ListItem->OverlayIndex is assigned value 2 when the Filename is 'something.lnk'.
But the overlay icon is not showing.  I'm sure I'm missing something.  To get overlay icons to work with my own TImageList objects I had to call ImageList->Overlay().  I wonder if I need to do the same with the Windows list, but I'm not sure what values to use then.

A: The overlay index returned by SHGetFileInfo() is 1-based, but the TListItem::OverlayIndex property expects a 0-based index, which it then converts to 1-based when updating the list item using the Win32 API.  So you need to subtract 1 when assigning the OverlayIndex:
ListItem->OverlayIndex  = (info.iIcon >> 24) - 1;

You DO NOT need to call TImageList::Overlay() when using a system image list.
Update: your subclass needs to look for the CN_NOTIFY message instead of WM_NOTIFY.  WM_NOTIFY is delivered to the ListView's parent window and reflected back to the ListView as CN_NOTIFY by the VCL.  Also, you need to use a reference when declaring your local LVITEM variable, otherwise you are modifying a copy instead of the original LVITEM that is in the message data.  Also, when assigning item.state and item.stateMask, you need to use the |= operator to append your overlay values to them instead of replacing the existing values that were assigned by the default handler.
void __fastcall TForm1::LVNewWindowProc(Messages::TMessage &Msg)
{
    if (LVOldWindowProc) LVOldWindowProc(Msg);
    if ((Msg.Msg == CN_NOTIFY) &&
        (reinterpret_cast<LPNMHDR>(Msg.LParam)->code == LVN_GETDISPINFOW))
    {
        LV_ITEM &item = reinterpret_cast<LV_DISPINFO*>(Msg.LParam)->item;
        TListItem *ListItem = ListView1->Items->Items[item.iItem];

        item.mask |= LVIF_STATE;
        item.state |= INDEXTOOVERLAYMASK(ListItem->OverlayIndex + 1);
        item.stateMask |= LVIS_OVERLAYMASK;
    }
}


text:
Q: Average number of words per sentence I have a dataset, which contains collection of text messages. I want to calculate the average words per sentence. But each message is in different format. ie, some messages ends with fullstop some messages not...
eg messages:
          Tiwary to rcb.battle between bang and kochi
          Dhawan for dc:)
          Warner to delhi.
          make it fast...

by using,
   words = messages.split() #get each words in the sentence
   leg_wrd = len(words)

but there is problem to find the end of sentence because it's not in similar. Then how can I identify the end of a sentence? And how to calculate the same using python 2.7.

A: This is not a trivial problem. I would recommend to use a 3rd party library like NTLK. This has a sentence tokenizer which works like this:
# Make sure that you have NLTK
from nltk.tokenize import sent_tokenize
text = "this's a sent tokenize test. this is sent two. is this sent three? sent 4 is cool! Now it's your turn."

sent_tokenize_list = sent_tokenize(text)

print(sent_tokenize_list)
# Will output ["this's a sent tokenize test.", 'this is sent two.', 'is this sent three?', 'sent 4 is cool!', "Now it's your turn."]


text:
Q: How to select range of cells instead of only 2 cells for strBody variable? VBA watch window shows "type mismatch" and Empty for values strBody variable and value when running this script.  I've confirmed the email portion of this script works.  I simply cannot select the range of cells I want.  Help?
I'd like to be able to select a range for the strBody variable.
If I replace the strBody variable with the following, everything works:
strBody = Str(Sheet1.Cells(1, 1)) & Str(Sheet1.Cells(1, 2))
Sub send_email()
Dim NewMail As Object
Dim MailConfig As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim strBody As Variant

strSubject = "Mail from Excel"
strFrom = "email@gmail.com"
strTo = "email@gmail.com"
strCc = ""
strBcc = ""
strBody = Str(ActiveWorkbook.Sheets("Sheet1").Range("A1:B2"))

A: Without seeing your data, you might consider building a UDF:
...
strBody = build_body(ActiveWorkbook.Sheets("Sheet1").Range("A1:B2"))
End Sub

Function build_body(rng As Range, Optional delimiter As String = " ") As String
Dim cel As Range
Dim tmpStr As String
For Each cel In rng.Cells
    If tmpStr <> "" Then tmpStr = tmpStr & delimiter & cel.Value
    If tmpStr = "" Then tmpStr = cel.Value
Next cel
Debug.Print tmpStr
build_body = tmpStr
End Function

With sample data:

Outputs: A1, B1, A2, B2.
Doing just Str(Sheet1.Cells(1, 1)) & Str(Sheet1.Cells(1, 2)) would output A1B1.


text:
Q: get index of for loop when using formset django template:

    {% for image in obj.images_set.all %}

  {% endfor %}

 {% for image in obj.images_set.all %}

                        {% endfor %}

Im using a for loop on images which has a image set ..Im using modals here so the id should be modal1,modal2 modal3 etc and get incremented on each looping ..But as of now ,it is not incrementing ...How to do this?The imageset for each loop has a maximum of 3 and min of one image!


text:
Q: In C++ why have va_start immediately followed by va_end? I see the following code in a few functions in a project I am trying to read and understand:
void Algo::descend(const enc_node* node, const char* option, ...)
{
    ...
    va_list va;
    va_start(va, option);
    va_end(va);
    ...
}

I understand variadic functions in principle but why would someone make a variadic function and then call va_start() followed immediately by va_end() with nothing in between? What does this achieve?

A:
In C++ why have va_start immediately followed by va_end?

No idea.

why would someone make a variadic function and then call va_start() followed immediately by va_end() with nothing in between?

No idea, that doesn't make much sense. It's like writing int a; and never using that variable. (Probably a sign of not enough coffee in programmers mind.)

What does this achieve?

Nothing.

The full function that you posted a link to gives more insight:
void Algo::descend(const enc_node* node, const char* option, ...)
{
  if (logdebug_enabled(LogEncoder)) {
    descendLevel++;
    printf("%d ",descendLevel);
    for (int i=0;i<descendLevel;i++) { printf(" "); }

    va_list va;
    va_start(va, option);
    va_end(va);

    fprintf(stdout, ">%s(", name());
    vfprintf(stdout, option, va);
    fprintf(stdout, ") %d;%d %dx%d %p\n",node->x,node->y,1<<node->log2Size,1<<node->log2Size,node);
  }
}

The function is invalid as all other such functions in the link you mentioned. Calling vfprintf and using va after va_end is undefined behavior. If it's an open project - help the community and notify the developer.


text: Q: In Detroit: Become Human, what is ra9? In the video game Detroit: Become Human, many of the deviants become obsessed with something (or someone) called "ra9". Has any source, either in-game or out of game, definitively established what ra9 is?


text:
Q: How to use nazrin gem to call AWS CloudSearch expr method? From here we can know that use expr function can get special data:
https://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching-locations.html
Use ruby nazrin gem also found the expr method:
https://github.com/tsuwatch/nazrin/blob/master/lib/nazrin/search_client.rb#L108
But when tried to get special data as:
def get_data
  City.search.expr("distance=haversin(#{params[:latitude], #{params[:longitude]}, 'latitude', 'longitude'})").start(0).query(params[:keyword]).execute
end

Got error:
Invalid syntax in 'expr' parameter: Unexpected character ('d' (code 100)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [column: 2]

How to use it?


text:
Q: How to communicate BOTH error and informational messages in a REST API? We have a legacy application that allows our developers to "add" messages via a ThreadLocal in Java.
The current SOAP endpoints will scoop these messages off the thread and then package them up in the response.
The endpoints also catch all exceptions and then marshal those exceptions via this same mechanism to normalize the passing of messages (be they informational, warning, or error).
These messages are rich objects (they have a code, severity, classification, and then the actual message text.)
This is nice in many ways because now we have a standard way to communicate meaningful messages to the user (or calling service) but it also makes using the API more challenging because now the client must pick out the messages from the response AND also pick out the real payload.
Any web service can communicate messages this way...but only a handful do.
I would like to start moving our application towards a REST API but I am struggling on how best to handle the messaging. I am not super keen on adding an envelope to each of our REST responses because this really pollutes the API.
The alternative appears to be adding these messages to custom HTTP headers. Is this the "preferred" approach? Remember I will have a list of one or more of these messages and I will likely have to serialize them as json as well.
Thanks.


text:
Q: Eclipse & angularjs validation error: Unexpected token for import and export I started to learn angular.js and build the hello world app according to the official angular site.
I'm working with Spring Tool Suite 3.8.4 and installed the AngularJS Eclipse 1.2.0 plugin and the test project was working fine without any validation errors.
After finishing this tutorial I made a git clone from this demo application, did all the installation steps, imported it as a project into Eclipse and configured it as an angular project (nature).
After all validation was done Eclipse showed me about 2500 errors with the message Unexpected token. I opened some files and it seems that the import and export keyword isn't recognized properly.
As the hello world app uses also these keywords and didn't have any validation errors I assume the reason could be a configuration problem. If i compare them in my project explorer i was wondering why in my hello world app was only a folder "TypeScript Resources (2.2.2)" and in this imported project there is also one folder/lib called "Javascript Resources". Might be ok, just something i noticed.
As im totally new to angular I have no clue what I could check. I read that the angular js support for the Eclipse IDE isn't perfect but these articles have been partly outdated as they were using Angular 1.x and 2.x.
Running the application with npm start in a terminal or "Run as" ==> ng serve" works fine without any problem.
Both applications (hello world and the cloned one) use Angular 4.x.
Does anybody have an idea? Do I need to provide more information?

A: At first just to clarify things, you have installed Angular2 Eclipse which is for Angular2, Angular4 and where you develop with TypeScript. AngularJS Eclipse is for Angular1 where you develop with JavaScript.
You error is a JavaScript Problem which comes from the JSDT plugins. It seems that you have added JSDT nature. I suggest you to remove JSDT nature from your project because you develop with TypeScript and not with JavaScript.
To do that you can edit your .project file and remove this line:
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>

If you need to open JavaScript file in an editor with validation, completion, etc, TypeScript IDE provide a JavaScript (Salsa) Editor which does that. You open your JS file with JavaScript (Salsa) Editor:

and after you benefit from the same feature than TypeScript editor:


text:
Q: How to extract elements from pytube stream? I am working with pytube to write an automated scripts which helps me download a YouTube video. I wanted to get the itag number of the highest resolution video.
The method get_highest_resolution() returns the stream of the highest resolution video:
highest_resolution_stream = yt_obj.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()

Its output looks like this:
<Stream: itag="18" mime_type="video/mp4" res="360p" fps="25fps" vcodec="avc1.42001E" acodec="mp4a.40.2" progressive="True" type="video">

Now I want to extract the value of itag from this pytube stream.

A: To extract itag, we just need to do use <stream>.itag:
highest_resolution_stream = yt_obj.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()
my_itag = highest_resolution_stream.itag


text:
Q: Strange behaviour of UITextField / cursor with NSTextAttachment I have quite straightforward code to add NSTextAttachment to UITextView:
override func viewDidLoad() {
    super.viewDidLoad()
    //textView.textDragInteraction?.isEnabled = false
    textView.becomeFirstResponder()
    textView.isEditable = true
    let image = UIImage(named: "dog")
    let textAttachment = NSTextAttachment()
    textAttachment.bounds = CGRect(x: 0, y: 0, width: (image?.size.width)!, height: (image?.size.height)!)
    textAttachment.image = image
    let attrString = NSAttributedString(attachment: textAttachment)
    textView.textStorage.insert(attrString, at: 252)
}

Works fine except when dragging image attachment UITextView becomes unresponsive, cursor disappears and it's not possible to drop attachment at desired position:
dragging image attachment
Slightly modifying code to:
textAttachment.contents = UIImagePNGRepresentation(image!) as Data?
attached image is not correct, but the rest works as expected, cursor position is visible, attachment drops at desired position.
dragging content attachment
Is it a bug? I have spend quite a lot of time finding the solution, unsuccessfully... I need draggable image attachment... Any help?
Thanks


text:
Q: Default angular input field value after second delete I have a simple input with ngModel.
HTML:
    <input type="number" min="0" [ngModel]=testField (ngModelChange) = setValue($event)>

{{testField}}

TS:
    testField = 5;

    setValue(value: number): void {
     if (value) {
       this.testField = value;
     } else {
       this.testField = 0;
     }
    }

When I delete value from input for the first time it set input value to 0 as expected, but if I delete this 0, input field stay empty. How can I set its value to 0 anyway, after deleting 0 second time ?
StackBlitz: click

A: You can watch for the keyup event and if the $event.target.value is === '', set value to 0.
  testField = 5;
  keepValueZero = $event => {
    if ($event.target.value === "") {
      $event.target.value = 0;
    }
  };
  setValue(value: number): void {
    if (value) {
      this.testField = value;
    } else {
      this.testField = 0;
    }
  }

<input type="number" min="0" [ngModel]=testField (ngModelChange) = setValue($event) (keyup)='keepValueZero($event)'>

{{testField}}

Demo Here


text:
Q: Change Color of AntD Button (background) I am aware there are other similar topics on this, but I was wondering how to make my situation work. I have not been able to make it work with available information so far.
I am trying to modify the background color of a Text button when the mouse hovers.
If I change my backgroundColor style inline of the button, it changes the appropriate area entirely. It seems there are no way to add an :hover functionality inline (I am using TS, shows up as an error. Even though it compiles, it has no effect).
If I use a SCSS module, I can change again the whole background color. But if I change the same property with the :hover functionality, it only affects the text part (see screenshot).
I've tried targeting more specifically the ant-btn-text, but to no effect still.
Would someone have an idea? I would like to avoid creating a state variable for this.

Edit: added portion of code and CSS as requested in comment

A: AntD classes generally override your own css stying. You can use !important to override that.

A: Ok so I found it (only post it now as it was getting late local time).
So compared to my original post, the & parent selector was necessary, and also adding !important made the trick.
So in my case, having:
.updateButton {
    &:hover:{
        background-color: red !important;
    }
}

overrode the default styling.
Thank you!


text:
Q: How to convert IHTMLImgElement to image I am automating Internet Explorer using SHDocVW.dll and MSHTML with C#, and I wish to save an image from the page to the disk (JPEG format).
I can't use the WebClient class to download the image; if I do it, I end up downloading the site's login page. I can't print the screen either, because the browser has to remain invisible during this process, running in the background.
I have tried to do the following:
IHTMLImgElement imgElement = ...;
IHTMLControlRange imgRange = ...;

imgRange.add(imgElement as IHTMLControlElement);
imgRange.execCommand( "copy", false, null );

This does nothing. I am not able to extract anything from the clipboard. Every solution I found didn't work for me.

A: Your webclient approach is probably missing cookies... see How do I log into a site with WebClient? for an example that handles cookies.
your code looks fine except the user has to change the security setting to enable clipboard access. If the image is cached on disk you can dig the WinInet cache after parsing the page for the image location.


text:
Q: Running Rails console in Sandbox mode in production Is it a good practice running rails console in sandbox mode in prod?
I'm looking for a good way to test things on the production server. rails console --sandbox seems like a good option: I can test whatever I need without any worry to affect the production.
After talking to other programmers, they are saying that the sandbox transactions might block other requests. That's why it's better to do rails console and just be careful with whatever you're doing.
The only piece of information that I found is Rails Command Line Guide. And of course there is nothing about how sandbox works and whatnot. Do you think that's ok to run rails console --sandbox on the prod? Why? Why not?

A: Following command is used to run rails console in sandbox mode in production environment
 RAILS_ENV=production rails c --sandbox


text:
Q: CSS Flexbox: Navigation is not stacking (becoming one column) I want my nagivation
 items to be side by side to each other like it currently is. But I want them to be on top of each other (1 column) when the screen size is 545 pixels or smaller.
The navigation is NOT changing to 1 column when it reaches 545 pixels.
I  have tried to add flex-direction: column
to the @media(max-width: 545px)
to nav ul

    nav {
  padding-left: 0px;
}

nav ul {
  display: flex;
}

nav ul li {
  list-style: none;
  margin-right: 50px;
}

nav ul li a {
  color: #8B8B8B;
  text-decoration: none;
  font-weight: bold;
  font-size: 17px;
  text-align: center;
}

nav ul li a:hover {
  color: #56B8AE;
  border-bottom: 1px solid;
  /* I WANT A ONE ROW STACK OF THE NAV ONCE THE SCREEN IS 545px or SMALLER */
  @media (max-width: 545px) {
    nav {
      padding-top: 0;
      padding-bottom: 30px;
      margin-top: 0;
      min-height: 100px;
      text-align: center;
    }
    nav ul {
      flex-direction: column;
    }
    nav ul li {
      border-top: solid 1px #e6ecf0;
      padding-bottom: 5px;
    }

  <link rel="stylesheet" href="style.css">

 Home

 Shop

 Music

I expected it to become one column at 545px and less. But it stays as one row instead.

A: You just forgot to close the nav ul li a:hover rule with a } before the media query (and then again at the end of the media query). If you add that, it works:

nav {
  padding-left: 0px;
}

nav ul {
  display: flex;
}

nav ul li {
  list-style: none;
  margin-right: 50px;
}

nav ul li a {
  color: #8B8B8B;
  text-decoration: none;
  font-weight: bold;
  font-size: 17px;
  text-align: center;
}

nav ul li a:hover {
  color: #56B8AE;
  border-bottom: 1px solid;
}

/* I WANT A ONE ROW STACK OF THE NAV ONCE THE SCREEN IS 545px or SMALLER */

@media (max-width: 545px) {
  nav {
    padding-top: 0;
    padding-bottom: 30px;
    margin-top: 0;
    min-height: 100px;
    text-align: center;
  }
  nav ul {
    flex-direction: column;
  }
  nav ul li {
    border-top: solid 1px #e6ecf0;
    padding-bottom: 5px;
  }
}

  <link rel="stylesheet" href="style.css">

 Home

 Shop

 Music

A: Just add flex-wrap: wrap; on the container. Note: not pertaining to your question, but you should also move  inside .

    nav {
  padding-left: 0px;
}

nav ul {
  display: flex;
  flex-wrap:wrap;
}

nav ul li {
  list-style: none;
  margin-right: 50px;
}

nav ul li a {
  color: #8B8B8B;
  text-decoration: none;
  font-weight: bold;
  font-size: 17px;
  text-align: center;
}

nav ul li a:hover {
  color: #56B8AE;
  border-bottom: 1px solid;
  /* I WANT A ONE ROW STACK OF THE NAV ONCE THE SCREEN IS 545px or SMALLER */
  @media (max-width: 545px) {
    nav {
      padding-top: 0;
      padding-bottom: 30px;
      margin-top: 0;
      min-height: 100px;
      text-align: center;
    }
    nav ul {
      flex-direction: column;
    }
    nav ul li {
      border-top: solid 1px #e6ecf0;
      padding-bottom: 5px;
    }

  <link rel="stylesheet" href="style.css">

 Home

 Shop

 Music


text:
Q: Divisão de registros listados em Lotes PHP Tenho uma listagem com 37 itens, retornando em forma de array do banco de dados na seguinte forma:
SELECT * FROM tabela WHERE id = '5';

Nesta listagem, eu tenho um dividendo:
$total = 37; // quantidade retornada do banco de dados
$dividir = 2; // quantidade que eu desejo dividir
$resultado = floor($total/$dividir); // arredondo para baixo

O total do resultado será 18. Sobram então 1 item.
O que eu preciso é inserir estes dados no banco de dados na seguinte forma:
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 1 (eu dividi por 2, então os primeiros 18 registros serão com lote 1) e os demais campos
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 2 (eu dividi por 2, então os outros 18 registros serão com lote 2) e os demais campos
E por fim, como sobrou um, eu preciso inserir como um terceiro lote
INSERT INTO tabela2 (total, lote, campo1, campo2)

O que representa: total = 37, lote = 3 (eu dividi por 2, então o que sobrou será o lote 3) e os demais campos
Como eu faria para que eu consiga inserir corretamente no banco de dados? Minha dúvida se resume apenas a divisão dos registros em lotes.

A: Modifiquei o código, veja se atende melhor:
<?php
$registros = [];
for($j = 0; $j < 51; $j++){
    $registros[$j] = "Registro " . $j;
}

$total = count($registros);
$dividir = 10;
$resultado = floor($total/$dividir);
$totalLotes = $dividir + ($total % $dividir > 0 ? 1 : 0);

echo "Total por lote: $resultado.
";
echo "Total de lotes:  {$totalLotes}.
";

$lote = 1;
$contador = 0;
foreach($registros as $chave => $registro){
    if($contador == $resultado){
        $contador = 0;
        $lote++;
    }
    $contador++;

    echo "INSERT INTO tabela2 ({$total}, {$lote}, {$registro}, {$chave})" . "
";

}

?>


text:
Q: Odoo 13 - Modify Journal Items when create Bill Vendor I have question about Vendor Bill.
When we create vendor bill, there is a journal items tab that  the data  will  be  generated when we choose Receipts.
I have requirement that user want to reformat the journal item, let say to add 1 account item of debit and credit.
Im looking the sourcode, and the journal items generated from this line :
moves_lines = self.env['stock.move'].browse([rec.id for rec in picking_ids.move_ids_without_package])
new_lines = self.env['account.move.line']
for line in moves_lines:
    new_line = new_lines.new(line._prepare_picking_account_move_line(self))
    #  if  i  comment  the  above  line,  the  journal  items  will  not  generate

    new_line.account_id = new_line._get_computed_account()
    new_line.stock_move_id = line.id
    new_line._onchange_price_subtotal()
    new_lines += new_line

My questions are :
How can i modify the journal items account format ?
If i comment the new_lines.new() it will not generate the journal items. But i don't know how  to modify the journal items generation.
For information the code is created by previous programmer but currently its not possible to contact them.
Thank you before

A: According to your piece of code, you "just" need to create a new account move line and add it to your record set (new_lines).
You will probably have to do it this way:
moves_lines = self.env['stock.move'].browse([rec.id for rec in picking_ids.move_ids_without_package])
new_lines = self.env['account.move.line']
for line in moves_lines:
    new_line = new_lines.new(line._prepare_picking_account_move_line(self))
    #  if  i  comment  the  above  line,  the  journal  items  will  not  generate

    new_line.account_id = new_line._get_computed_account()
    new_line.stock_move_id = line.id
    new_line._onchange_price_subtotal()
    new_lines += new_line

# do your computation stuff here
dict_of_values = {
    debit: DEBIT_VALUE,
    credit: CREDIT_VALUE,
    account: ACCOUNT_ID,
    **any_other_required_values
}
new_account_move_line = self.env['account.move.line'].new(dict_of_values)
new_lines += new_account_move_line

Another way of doing that is to gather account_move_lines you want to create and to write them directly on your account_move.
amls_to_write = []
amls_to_write += [(0, 0, aml_dict_of_values)]
your_account_move.write({'line_ids': amls_to_write})

regarding the "cryptic" (0, 0, values), it corresponds to that:
(ORM_METHOD_NUMBER, ID_OF_RECORD, VALUES_OF_RECORD)
I let you have a look at the ORM methods: (don't forget to change the link for the version you are developing in)
https://www.odoo.com/documentation/14.0/developer/reference/addons/orm.html#common-orm-methods
Note that the AccountMove model has a lot of constraint and that you have to balance the account_move_line together for the global balance of the account_move to be 0. (basic accounting stuff)
By the way, the variable names are highly unclear and there are rooms for confusion here. You should rename those to match what they are.

*

*moves_lines and line are stock_move -> stock_moves and stock_move

*new_lines and new_line are account_move_line -> account_move_lines and account_move_line (or aml if it's too long)


text:
Q: Read a matrix from a file which contains a header I have a file which contains a header(specific to a file used by octave) and I have to read the matrix contained in the file. The idea is that I have a function and the file location is stored in a string let's say location. If I try to do load(location) I get some parse error and that matrix will not be load.
    function [extract] = read(location)
    matrix = ?;
    end


text:
Q: A proof validation about compactness We know that in a metric space $(X,d)$ a subset $K$ of $X$ is compact iff every sequence in $K$ has a convergent subsequence that converges to a point of $K$.
I want to prove the '$\Longrightarrow$' part.Here is my attemt:
Suppose that  $\exists x_n$$\in$$K$ such that every subsequence of $x_n$ is not convergent.
Thus for every $x\in$$K$ ,$\exists \epsilon_0$ such that the open ball $B(x,\epsilon_0)$ that contains $x$ has a finite number of terms of $x_n$.
Now the family of subsets $\{B(x,\epsilon_0): x\in$ $K\}$ is an open cover of $K$ thus there exists a finite subcover of $K$ from our assumption.
$\exists x_1,,,,,x_n$ $\in$$K$ such that $K\subset \bigcup\{B(x_i,\epsilon_0):i=1,2,,,n\}$.
And we deduce that $x_n$ is a finite sequence.
This is a contradiction.
Is this proof valid?
Thank you in advance!


text:
Q: Parse IP and Download-Total from mikrotik I wanna extract IP and download-total from mikrotik command /queue simple print stat
Here's some example :
0    name="101" target=192.168.10.101/32 rate=0bps/0bps total-rate=0bps
  packet-rate=0/0 total-packet-rate=0 queued-bytes=0/0
  total-queued-bytes=0 queued-packets=0/0 total-queued-packets=0
  bytes=17574842/389197663 total-bytes=0 packets=191226/308561
  total-packets=0 dropped=9/5899 total-dropped=0

1    name="102" target=192.168.10.102/32 rate=0bps/0bps total-rate=0bps
  packet-rate=0/0 total-packet-rate=0 queued-bytes=0/0
  total-queued-bytes=0 queued-packets=0/0 total-queued-packets=0
  bytes=65593392/183786457 total-bytes=0 packets=163260/166022
  total-packets=0 dropped=175/2403 total-dropped=0

2    name="103" target=192.168.10.103/32 rate=0bps/0bps total-rate=0bps
  packet-rate=0/0 total-packet-rate=0 queued-bytes=0/0
  total-queued-bytes=0 queued-packets=0/0 total-queued-packets=0
  bytes=3263234/67407044 total-bytes=0 packets=41437/52602
  total-packets=0 dropped=0/546 total-dropped=0

All that I need is :
192.168.10.101 389197663
192.168.10.102 183786457
192.168.10.103 67407044

But I get
target=192.168.10.101/32
bytes=17574842/389197663
target=192.168.10.102/32
bytes=65593392/183786457
target=192.168.10.103/32
bytes=3263234/67407044

I try it with grep -oP 'target=.*?\ |[^\-]bytes=.*?\ ' | sed 's/^ //g'.
So, how can I parse it?  Sorry for bad english..

A: Just continue your line of parsing with another pipes  (most easy way i think)
grep -oP 'target=.*?\ |[^\-]bytes=.*?\ ' file | sed 's/^ //g' | sed -r 's/target=([^/]*)[/].*/\1/; s/bytes=[^/]*[/]//' | sed 'N; s/\n/ /'

output
192.168.10.101 389197663
192.168.10.102 183786457
192.168.10.103 67407044

A: sed '/^[0-9]\{1,\}[[:blank:]]\{1,\}name/,/^[[:blank:]]*$/ {
   /^[0-9]/{
      s#.*target=\([^/]*\).*#\1#;h;d
      }
   \#^[[:blank:]]*bytes=[0-9]*/\([0-9]*\).*# !d
   s//\1/
   G
   s/\(.*\)\n\(.*\)/\2 \1/p
   }
   d
   ' YourFile

A bit long but do the job in 1 sed
awk '{
   if ( $3 ~ /target=/ ) split( $3, aIP, "[=/]")
   if ( $1 ~ /^[[:blank:]]*bytes=[0-9]*/ ) {
      split( $1, aByt, "/")
      print aIP[2] " " aByt[2]
      }
   }' YourFile

same in awk
if always same exact structure
awk 'BEGIN{ RS="" }
     { split( $3, aIP, "[=/]"); split( $12, aByt, "/")
       print aIP[2] " " aByt[2]
     }' YourFile


text:
Q: How do extractors get damaged? Extractors can take damage while deployed. That's as much info as the game gives, and that's obviously not enough.
What are the specific rules for deployed extractors taking damage? Are they only vulnerable during specific parts of their work cycles? How much damage do they take per hit? Does it matter what planet it's deployed to? Is there any way to avoid this damage?
And as always, I'll record my own observations here and see if a pattern emerges.

*

*Titan Extractor, deployed to Mercury, took 29% damage while active.

*Titan Extractor, deployed to Mercury, took 37% damage while active.

A: yes, the extractors:

*

*take damage (only) while their work cycles. when they are done and still alive, they don't loose any  more health

*the more damage the higher the planet

on earth i think i never took more than 45% damage. can always do two runs without loosing it entirely there
It is also worth noting that Extractors will heal over time if you keep them put away, not extracting or waiting on a planet.

A: An extractor can't die in one run, so it can't get hit more then 99%. If you deploy your extractor at 100% then he'll live we's done. So extracting overnight isn't a problem if you use a 100% health extractor.
What I have done is: I made multiple extractors but I can only extract one at a time because of my mastery rank. but when one extractor is damaged and is ready to come back to me I can deploy another one that I made and then the one that got damaged can heal up etc.


text:
Q: iTunes not changing my app status after i uploaded my iOS app I just uploaded a binary to itunes from Xcode. But when I checked
the iTunes page it says waiting for upload. I do not know why. This
problem happens only after the new UI changes on iTunes side.
Any help that might be appreciated

A: It may be still processing. Somewhere in the iTunes Connect documentation it says this might take some time. If after 24 hours nothing has changed, I'd recommend you contact their support.

A: This happened to me and I just uploaded the binary again. Third time it showed up. It takes about 10 min. of processing before you can select the binary for Submitting.


text: Q: Saml2 spring-security single logout It looks like the existing spring-security Saml2 configuration does not have the single logout functionality according to https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#saml2. I already have the logout url for openAM (ForgeRock), but what's the best way to handling logout using spring-security for Saml2?


text:
Q: Casting with #if in C Why this code gives an error:
#include <stdio.h>
#define Rep (int)6
int main(){
     #if Rep==6
         printf("T");
     #else
         printf("F");

     #endif

return 0;
}

*

*Why does it refuse the casting?

*Is it a 'preprocessor error' or a 'compiler error'?

A: This is a preprocessor error. It happens because the preprocessor does not understand how to cast a variable. You cannot use any C code with #if, just simple numbers, or macros which expand to a number.
If you cannot modify Rep, you can work around this with a helper macro, which removes the casting from the beginning:
#include <stdio.h>

#define X(x)
#define Y(x) X x
#define Rep (int)6

int main(void) {
#if Y(Rep) == 6
    printf("%d\n", Y(Rep)); // prints 6
#endif
    return 0;
}

A: Preprossor macros that combine casts and that still should work in #if are easy to write: you just add a little + before the number. In your case
#define Rep ((int)+6)

The preprocessor replaces identifiers that it doesn't know by 0 so the end result is the same value.
But also, the cast in your Rep macro by itself is quite useless. 6 is an int, anyhow. So better avoid a cast for all integer types that have their own literals, combinations of U and L as suffix should do in most cases.


text:
Q: cakePHP associated data not retrieved This problem's been bashing my brains for days. When i perform a find('all') on my Department model, no associated data is fetched. Here's my Department model:
<?php
App::uses('AppModel', 'Model');

class Department extends AppModel {

public $displayField = 'name';
//The Associations below have been created with all possible keys, those that are not needed can be removed

public $belongsTo = array( ///check
    'District' => array(
        'className' => 'District',
        'foreignKey' => 'district_id'
    )
);
public $hasMany = array(
    'Group' => array(
        'className' => 'Group',
        'foreignKey' => 'department_id' ///check
    ),
    'Request'=>array(
        'className' => 'Request',
        'foreignKey' => 'department_id',
    ),
    'DepartmentPosition'=>array(
        'className'=>'DepartmentPosition',
        'foreignKey'=>'department_id',
        'dependent'=>true
    ),
);

}
When I do find('all'), it returns all fields from every department in the database, but no associated data at all. in the departments controller:
$departments = $this->Department->find('all');
$this->set(compact('departments'));

It feels like i have a problem in the model because I'm having no issues with any of the other models and returning associated data, including one's related to Department. For instance, I can find all of the Departments related to a District.
Thanks in advance!

A: Incorrect model file naming is the most common cause of your model file not being read and cake using an AppModel instance for the table. So check your model's file name. Ensure it's Department.php. In your controller do debug(get_class($this->Department)); its should return "Department" and not "AppModel".
Assuming your model file is loaded properly and you still have problem most likely cause is model's $recursive property is set to -1, perhaps in AppModel.

A: You should use following :
$this->Department->recursive = 1;
$departments = $this->Department->find('all');
$this->set(compact('departments'));


text:
Q: Problems with Pyramid Traversal and Browsers Back-Button I'm using Pyramids Traversal and got some problems. Let us say, I've this config:
config.add_route('main_dis','/dis/{params}/go')
config.add_route('ajax_R1', '/dis/{url:.*}ajax_R1')
config.add_route('ajax_R2', '/dis/{url:.*}ajax_R2')

whereby the first one is a view config for chameleon, and the second and third one for json. If I call www.example.com/dis/A/go, an ajax request will get information by calling ajax_R1. Afterwards the user can click something and go to www.example.com/dis/B/go, which calls ajax_R2. If the user want to navigate back from B towards A, the ajax request is fired, but pyramids does not finds the suitable view, so that the notfound_view_config is called. Does someone has an idea for this behaviour?
One "dirty fix" is to check the path-variable in the request of the notfound_view_config and calling the suitable method, but this is very dirty :(
Thanks,
Tobias
P.S.: Hopefully my problem will not be taken the wrong way :)


text:
Q: What is the name of this theorem or lemma? Real analysis:  $$x, f(x), g(x) \in \mathbb{R}$$
If $f(x) = g(x)$ "almost everywhere" in the interval $a \le x \le b$ (that is every value in the interval other than no more than a countably infinite number of discrete "points" or values of $x$), then
$$ \int\limits_a^b f(x) \ dx = \int\limits_a^b g(x) \ dx $$
i remember this from Real Analysis in college (had a text by Royden or someone like that).  what is this fact called?

A: $f = g$ a.e. means that the set $\{x\mid f(x) \neq g(x)\}$ has $0$ Lebesgue measure. It might not be countable. Consider $f = 0$ and $g = \chi_S$, where $S$ is the Cantor set.
This statement is the identity of indiscernibles for the $L^1$ metric. In the $L^1$ space, (or the space of integrable functions on $[a,b]$) functions that agree a.e. are considered the same. This manifestation makes $L^1$ a metric space with the metric $$\lVert f - g\rVert = \int_a^b |f-g|\,dx$$


text:
Q: Remove a string from a Ruby file when it matches a regex I'm writing a little script in Ruby that removes comments from Ruby files:
#!/usr/bin/ruby

def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /(^\s*#|^\t*#)(?!\!).*/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end

puts "Fetching all files in current directory and uncommenting them"
# fetching all  files
files = Dir.glob("**/**.rb")
# parsing each file
files.each do |file|

  #fetching each line of the current file
  uncomment file

end

I am stuck on how to remove these lines that match the regex in the #todo section, it would be great if someone could help!

A: change:
def uncomment(file)
  File.readlines(file).each do |line|
    if line =~ /#(?!\!).+/
      puts line + " ==> this is a comment"

      #todo: remove line from the file

    end
  end
end

to:
def uncomment(file)
  accepted_content = File.readlines(file).reject { |line| line =~ /#(?!\!).+/ }
  File.open(file, "w") { |f| accepted_content.each { |line| f.puts line } }
end

You would be reading the accepted lines into an array(accepted_content), and writing back that array into the file

A: I would do this by creating a temporary file:
open('tmp', 'w') do |tmp|
  File.open(file).each do |line|
    tmp << line unless line =~ /#(?!\!).+/
  end
end
File.rename('tmp', file)


text:
Q: Using .htaccess to mask a domain? So here's the scenario:
The domain I have is www.abc.com and I want to point it to  (which belongs to another company).
Question: How would I use .htaccess to forward and mask the url so that it stays as www.abc.com?
In terms of security, is there any point in buying a digital certificate for www.abc.com?

A: You could uh, run it through a proxy, which will TOTALLY mask it.
You put this in your httpd.conf file, not the .htaccess:
<VirtualHost *:80>
    ServerName www.abc.com
    ServerAlias abc.com
    ProxyRequests     Off
    ProxyPreserveHost On
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
    ProxyPass / http://site-you-want-2-show.com:80/
    ProxyPassReverse / http://site-you-want-2-show.com:80/
  <Location />
    Allow from all
  </Location>
</VirtualHost>

You can try with ProxyPreserveHost both On and Off, and testing if the images display properly and the addresses of objects show your domain instead.
WARNING: This is not legal if you do not have explicit permission from the company you are trying to show's website. Perhaps you can then just make your homepage an iFrame.
As for certificates: It can be done, see here: http://ssl-proxy.plz.re (short-url)

A: .htaccess files cannot "mask" a domain but could use a reverse proxy if the module is installed.
In most case, the "masked" website will refer to full urls and the "mask" will not work for long.
See what @mesh proposed.


text:
Q: foreach solo muestra el ultimo dato C# Cargo 2 listas para buscar ciertos atributos y guardarlos en una nueva lista, y aunque lo hace bien hasta cierto punto solo guarda el ultimo objeto que recorre el foreach.
         foreach (var i in remeresu)
        {
            foreach (var t in trabajadores)
            {

                if (t.nrt_ruttr == i.nrt_ruttr && i.cod_conce == 910)
                {
                    listpapeleta.rutTra = t.nrt_ruttr;
                    listpapeleta.nombre = t.nom_nomtr + " " + t.nom_appat;
                    listpapeleta.fechaPago = (DateTime)i.fec_pago;
                    listarPapeleta.Add(listpapeleta);
                }

            }

        }

y esta la retorno a una vista
return View(listarPapeleta);

A: El problema que tienes es que estas modificando la misma referencia del objeto listpapeleta en cada iteración del bucle. Esto provoca que todos los elementos que se almacenen en la lista contengan exactamente la misma información de la última modificación que sufrió el objeto. Para arreglarlo tienes que crear un nuevo objeto antes de modificar los atributos de este:
foreach (var i in remeresu)
{
    foreach (var t in trabajadores)
    {
        if (t.nrt_ruttr == i.nrt_ruttr && i.cod_conce == 910)
        {
            /* Reservar espacio en memoria */
            listpapeleta = new ListPapeleta(); // O el nombre que le tengas dado a esa clase

            /* Modificar el nuevo objeto */
            listpapeleta.rutTra = t.nrt_ruttr;
            listpapeleta.nombre = t.nom_nomtr + " " + t.nom_appat;
            listpapeleta.fechaPago = (DateTime)i.fec_pago;

            /* Añadir a la lista */
            listarPapeleta.Add(listpapeleta);
         }
     }
}

A: Hola no se si te sea de mucha ayuda lo siguiente, lo que yo hice no se si sea la manera correcta u optima pero a mi me ayudo, lo que realice fue crear dos nuevas listas en el código, una en donde hago referencia a la consulta, y otra en donde voy agregando los resultados por cada iteración.
      List<ListPapeleta> datos= new List<ListPapeleta>();
     foreach (var t in trabajores)
          {
            if (t.nrt_ruttr == i.nrt_ruttr && i.cod_conce == 910)
               {
                     listpapeleta lst = new ListPapeleta();

                      lst.rutTra = t.nrt_ruttr;

                      datos.Add(com); //lo agrego
                 }

             }
                //asi al retorna habra recorrido y agregado a la lista los elementos y retornara todos los valores y no solo el ultimo
                return datos;

Tenia una misma situación de otra forma: pero igual te dejo la pregunta
¿Cómo devolver todos los resultados de una consulta hecha dentro de un for each en C#?


text:
Q: oAuth: client credentials flow and execution user
Hey folks.
I am trying to obtain a token using the client_credentials flow and have had little success.
What I did so far:

*

*Create the Connected App

*Enabled IP Relaxation

*Managed successfully to get a token using the password flow (hitting the same token endpoint)

*edit #1 After the first comment, I also added the Run As as below.

Again, my problem is stated in the error message Salesforce returns to my POST:
{
    "error": "invalid_grant",
    "error_description": "no client credentials user enabled"
}

Any clues on what would be the solution? I am inclined to say I need some sort of Execution User activated ~~but so far I am clueless about where to add that (if that is a thing)~~edit #1. A Google search did not return anything useful.

A: I have checked in my personal org for the same implementation and faced the same issue. As my user is not API only user I faces it. I guess this is same in your scenario as well.
The users with " API Only " will not be able to log in to salesforce through UI.

API Only - Specifies that the user can only log in through the API. This prevents the user from being used for any purpose other than integration scenarios.

Please find the article for more details on this permission


text:
Q: Linear regression with upper and/or lower limits in R? Is there a way to run a linear regression with upper and/or lower limits
on the coefficients in R?

A: Yes, you can do this in Lavaan.
Here's an example. We fit a regression model, and find an estimate of 0.10. Then fit a model using lavaan, and get the same parameter estimate. Then fit the model with a constraint that b1 has to be greater than 0.
library(lavaan)
set.seed(1234)
df <- as.data.frame(matrix(rnorm(500), ncol=2))
names(df) <- c("x", "y")
summary(glm(y ~ x, data=df))

lavModel1 <- 'y ~ b1*x'

summary(sem(lavModel1, df))

lavModel2 <- 'y ~ b1*x
  b1 > 0'
summary(sem(lavModel2, df))

A: Yes, you can do it by re-defining linear regression as an optimization problem (a residual sum of squares cost function for example) and solving it using the constraints you want. So to use the numbers as the example from @Jeremy:
(Note that in this example we are fitting a model without an intercept)
set.seed(1234)
df <- as.data.frame(matrix(rnorm(500), ncol=2))
names(df) <- c("x", "y")
CostFunction <- function(theta){sum( (df$y - theta*df$x)^2)}
theta_0 =1;
theta_opt <- optim(fn= CostFunction, lower=0, par = theta_0, method="L-BFGS-B")

Ultimately any package you wish to use for constrained regression will do the same thing: formulate a cost function and solve a constrained optimization problem. In the case of ordinary least squares as the one shown here "ordinary" optimizers using "simple" BFGS variants will do just fine; harder problems (eg. GLMM) will require more exotic beasts like BOBYQA.


text:
Q: Flutter android release apk while installing over old version giving app not installed error Previously I have uploaded android native application on play store. Now I want to replace existing application with new flutter application. After signing I uploaded app on play store alpha channel. But while upgrading app giving error app not installed.
Note : I have followed flutter documentation steps while creating apk.
Can you help ?

A: It is an old question, but i just had the same problem and found a solution for me.
make sure that:

*

*both have the same Signed Certificate

*the new App APK has a higher version code then installed app

You can find out which version code your apk has with android studio - build:  analyse apk and look at the AndroidManifest.xml.
As mentioned in https://medium.com/@ralphbergmann/versioning-with-flutter-299869e68af4 the flutterversioncode is taken from the build number in the pubspec.yaml
In my case the version code of the old app was 4, although i did not set any build number in my old pubspec.yaml file.
Changing the version of my app to x.x.x+5 did solve the issue for me.

A: To confirm

*

*If both are signed by same certificate use this command to check certificate details look for validation time of the both the signed apk.

*If they are indeed signed by same certificate the go to Build>Analyse APK (add path of your signed apk)