text:
Q: Ktor App's Main Method Not Called When Deployed to AppEngine Issue
The Ktor application's main method is not called when deployed to AppEngine. In the applications's main method is logic to retrieve content from an API request based on a Timer and save that information to a Firestore database which a client consumes.
This logic currently works when deployed in a Jar to AppEngine. However, implementing this with Ktor would save deploy time and help future proof the backend service if endpoints are required.
Expected
The Ktor application's main method is called once the app is deployed to AppEngine similar to how an application's main method is called when ran in IntelliJ.
Actual
The main method is only called once the app's hosted route is called.
ie: https://[yourProjectName].appspot.com
Setup
Main Method
import io.ktor.application.Application
fun Application.main() {
    // App logic here.
}

build.gradle
buildscript {
ext.kotlin_version = '1.3.10'
ext.ktor_version = '1.0.0'
ext.appengine_version = '1.9.60'
ext.appengine_plugin_version = '1.3.4'
ext.junitJupiterVersion  = '5.0.3'

repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.google.cloud.tools:appengine-gradle-plugin:$appengine_plugin_version"
    classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
    }
}

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'war'
apply plugin: 'com.google.cloud.tools.appengine'

sourceSets {
    main.kotlin.srcDirs = [ 'src/main/kotlin' ]
}

sourceCompatibility = 1.8

repositories {
    jcenter()
    mavenCentral()
    maven { url "https://kotlin.bintray.com/ktor" }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    implementation "io.ktor:ktor-server-servlet:$ktor_version"
    implementation "io.ktor:ktor-html-builder:$ktor_version"
    providedCompile "com.google.appengine:appengine:$appengine_version"
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
    implementation 'com.google.firebase:firebase-admin:6.3.0'
    implementation 'com.google.apis:google-api-services-youtube:v3-rev204-1.23.0'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    // JUnit Jupiter API and TestEngine implementation
    testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
    testCompile("org.assertj:assertj-core:3.10.0")
    // To avoid compiler warnings about @API annotations in JUnit code
    testCompileOnly('org.apiguardian:apiguardian-api:1.0.0')
}

kotlin.experimental.coroutines = 'enable'

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

task run(dependsOn: appengineRun)

appengine {
    deploy {
    version = 'media-staging-1201181257pm'
    }
}

src/main/resources/application.conf
ktor {
    application {
        modules = [ InitializationKt.main ]
    }
}

src/main/webapp/WEB-INF/
appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <threadsafe>true</threadsafe>
    <runtime>java8</runtime>
</appengine-web-app>

web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <servlet>
        <display-name>KtorServlet</display-name>
        <servlet-name>KtorServlet</servlet-name>
    <servlet-class>io.ktor.server.servlet.ServletApplicationEngine</servlet-class>
        <!-- path to application.conf file, required -->
        <init-param>
            <param-name>io.ktor.config</param-name>
            <param-value>application.conf</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>KtorServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

A: Thank you to Gabriel Machado on Kotlin Slack for answering this.
Gabriel recommends using a Cron Job as opposed to a Timer Task because there may be issues with a Timer thread based on scaling type.

A: GAE probably expects your app to look like a Java app (e.g., a Java style "main", not a Kotlin style "main").
Look at this for more info on how to do this: How to run Kotlin class from the command line?


text:
Q: Ошибка при компиляции java программы Я написал следующую программу. Файл создан в eclipse.
package org.myorg;

import java.io.*;
import java.util.*;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

public class ParallelIndexation {

public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
     private final static IntWritable zero = new IntWritable(0);
     private Text word = new Text();
     public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
        String line = value.toString();
        int CountComputers;
        //DataInputStream ConfigFile = new DataInputStream( new FileInputStream("countcomputers.txt"));
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // путь к файлу
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String result = br.readLine(); // читаем как строку
        CountComputers = Integer.parseInt(result); // переводим строку в число
        //CountComputers=ConfigFile.readInt();
        in.close();
        fstream.close();
        ArrayList<String> paths = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(line, "\n");
        while (tokenizer.hasMoreTokens())
        {
          paths.add(tokenizer.nextToken());
        }
        String[] ConcatPaths= new String[CountComputers];
        int NumberOfElementConcatPaths=0;
        if (paths.size()%CountComputers==0)
        {
            for (int i=0; i<CountComputers; i++)
            {
                ConcatPaths[i]=paths.get(NumberOfElementConcatPaths);
                NumberOfElementConcatPaths+=paths.size()/CountComputers;
                for (int j=1; j<paths.size()/CountComputers; j++)
                {
                    ConcatPaths[i]+="\n"+paths.get(i*paths.size()/CountComputers+j);
                }
            }
        }
        else
        {
            NumberOfElementConcatPaths=0;
            for (int i=0; i<paths.size()%CountComputers; i++)
            {
                ConcatPaths[i]=paths.get(NumberOfElementConcatPaths);
                NumberOfElementConcatPaths+=paths.size()/CountComputers+1;
                for (int j=1; j<paths.size()/CountComputers+1; j++)
                {
                    ConcatPaths[i]+="\n"+paths.get(i*(paths.size()/CountComputers+1)+j);
                }
            }
            for (int k=paths.size()%CountComputers; k<CountComputers; k++)
            {
                ConcatPaths[k]=paths.get(NumberOfElementConcatPaths);
                NumberOfElementConcatPaths+=paths.size()/CountComputers;
                for (int j=1; j<paths.size()/CountComputers; j++)
                {
                    ConcatPaths[k]+="\n"+paths.get((k-paths.size()%CountComputers)*paths.size()/CountComputers+paths.size()%CountComputers*(paths.size()/CountComputers+1)+j);
                }
            }
        }
        //CountComputers=ConfigFile.readInt();
        for (int i=0; i<ConcatPaths.length; i++)
        {
            word.set(ConcatPaths[i]);
            output.collect(word, zero);
        }
     }
}

public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
    public native long Traveser(String Path);
    public native void Configure(String Path);
    public void reduce(Text key, IntWritable value, OutputCollector<Text, LongWritable> output, Reporter reporter) throws IOException {
        long count;
        String line = key.toString();
        ArrayList<String> ProcessedPaths = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(line, "\n");
        while (tokenizer.hasMoreTokens())
        {
          ProcessedPaths.add(tokenizer.nextToken());
        }
        Configure("/etc/nsindexer.conf");
        for (int i=0; i<ProcessedPaths.size(); i++)
        {
            count=Traveser(ProcessedPaths.get(i));
        }
        output.collect(key, new LongWritable(count));
      }
    static
    {
        System.loadLibrary("nativelib");
    }
}

public static void main(String[] args) throws Exception {
      JobConf conf = new JobConf(ParallelIndexation.class);
      conf.setJobName("parallelindexation");
      conf.setOutputKeyClass(Text.class);
      conf.setOutputValueClass(LongWritable.class);
      conf.setMapperClass(Map.class);
      conf.setCombinerClass(Reduce.class);
      conf.setReducerClass(Reduce.class);
      conf.setInputFormat(TextInputFormat.class);
      conf.setOutputFormat(TextOutputFormat.class);
      FileInputFormat.setInputPaths(conf, new Path(args[0]));
      FileOutputFormat.setOutputPath(conf, new Path(args[1]));
      JobClient.runJob(conf);
  }
}

При попытки компиляции в операционной системе Nexenta Illumos (solaris) командой
javac -classpath hadoop-examples-1.0.1.jar -d folder/classes folder/src/ParallelIndexation.java

выдало следующую ошибку
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:23: error: unmappable character for encoding UTF8
        FileInputStream fstream = new FileInputStream("/usr/countcomputers.txt"); // ���� � �����
                                                                                ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                          ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                           ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                            ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                             ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                              ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                               ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                 ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                  ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                   ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                     ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                      ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                       ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                        ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                         ^
folder/src/ParallelIndexation.java:26: error: unmappable character for encoding UTF8
        String result = br.readLine(); // ������ ��� ������
                                                          ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                      ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                       ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                        ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                         ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                          ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                           ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                            ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                             ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                              ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                 ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                  ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                   ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                    ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                     ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                       ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                         ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                          ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                           ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                            ^
folder/src/ParallelIndexation.java:27: error: unmappable character for encoding UTF8
        CountComputers = Integer.parseInt(result); // ��������� ������ � �����
                                                                             ^
46 errors

Как поменять в eclipse кодировку файла?
A: выделяем файл в package explorer или navigator. жмем alt+enter открывается окошко в котором можно поменять кодировку. аналогичным образом можно установить кодировку по умолчанию для project. а еще лучше через настройки поменять кодировку на utf8 сразу для workspace

redpajama_set_name: RedPajamaStackExchange


text:
Q: SortedDictionary duplicate keys? Okai, i have the following method:
public void Insert(SortedDictionary<byte[], uint> recs)
{
    SortedDictionary<byte[], uint> records = new SortedDictionary(recs, myComparer);
}

What I am hoping to achieve is to sort the records in "recs" with a new rule specified by "myComparer" which implements IComparer. It pretty much does so, but I get hit by an exception with the following message:

An entry with the same key already
  exists.

I am wondering how this is possible since "recs" is already a dictionary with about 130k keys.

    public int Compare(byte[] a, byte[] b)
    {
        return  Inhouse.ByteConverter.ToString(a).CompareTo(
                    Inhouse.ByteConverter.ToString(b));
    }

(it's just a snipette..)

A: If "recs" has a different comparer than the one you inject into records you may get duplicates; that is if "recs" compares by object reference and myComparer compares the actual bytes, you will have collisions.

A: Check the comparer code:

Every key in a SortedDictionary(Of
  TKey, TValue) must be unique according
  to the specified comparer; therefore, every key in the source dictionary must also be
  unique according to the specified comparer.

with your new comparer, 2 different keys with normal byte[] comparaison may become equal.
It's what msdn says...

A: You must be using the same Dictionary object in the calling method. So I imagine your code is something like this:
 SortedDictionary<byte[], uint> dic = new SortedDictionary<byte[], uint>();
 foreach (var thing in things)
 {
     dic.Clear();
     Populate(dic);
     Insert(dic);
 }

Where it should be like this:
SortedDictionary<byte[], uint> dic = new SortedDictionary<byte[], uint>();
foreach (var thing in things)
{
    dic = new SortedDictionary<byte[], uint>();
    Populate(dic);
    Insert(dic);
}

Can you post the code that is calling your Insert method?


text:
Q: Instance variable always returning zero I have an instance variable array:
       @interface ChannelsVC ()
        {
        NSArray *arrayofFrequencies;
        }
    }
    @end

@implementation ChannelsVC
......

made its allocation in the ´viewDidLoad´
arrayofFrequencies=[[NSArray alloc]init];

Then, I'm inserting data in the array from a JSON data source:
-(void)GetFrequencies{

    NSString *urla=@"http://xxxxxxxx";
    NSString *uria = [urla stringByAppendingString:self.lien_satellite];
    NSURL *urlFrequencies= [ NSURL URLWithString:uria];

    NSLog(@"Frequencies URI: %@",uria); //correct URI

    NSURLRequest *request = [NSURLRequest requestWithURL:urlFrequencies];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];

        NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);//the count here is correct, I have data in the array

     } failure:nil];

    [operation start];

 }

The problem is when wanting to make a UITableView that its number of sections is ´[arrayofFrequencies count];´ , it's always returning ´0´ ! It's an instance variable and it's returning zero outside the ´GetFrequencies´ function.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"number of sections %ld",(long)[arrayofFrequencies count]); // always returns 0
    return [arrayofFrequencies count];
}

Am I doing something wrong?
Thank your for helping.
Console output:
013-06-25 12:58:00.163 Frequencies[840:c07] number of sections 0
2013-06-25 12:58:00.165 Frequencies[840:c07] number of sections 0
2013-06-25 12:58:00.641 Frequencies[840:c07] Frequencies count: 4

A: Call [tableView reloadData] after
NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);//the count here is correct, I have data in the array

Point to understand is in viewDidLoad tableView delegates are called. At that time array count is zero. Later array is filled with object.  reloadData method call delegate method of table again.

A: Your Log Consol show it very clear that your datasource method called before your data load.
Which is very normal because you have setup datasource in storyboard(or interface) or in viewDidLoad.
You just have to reload your UITableView after dataload
Try this:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];

        [tableView setDataSource:self];
        [tableView reloadData];

     } failure:nil];

You should remove Datasource from interface builder or storyboard or viewDidLoad so UITableView dont reload it self twice.

A: Possible guess for this is tableView delegate is getting called earlier but the response from server is coming after some time so after getting the response try to reload the tabview below is the code.
    -(void)GetFrequencies{

        NSString *urla=@"http://xxxxxxxx";
        NSString *uria = [urla stringByAppendingString:self.lien_satellite];
        NSURL *urlFrequencies= [ NSURL URLWithString:uria];
        NSLog(@"Frequencies URI: %@",uria); //correct URI
        NSURLRequest *request = [NSURLRequest requestWithURL:urlFrequencies];
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

            arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];
            NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);
            // reload the table here
            [tableView reloadData];
         } failure:nil];
        [operation start];
    }

Try doing this.


text:
Q: Фильтрация внутреннего массива в MongoDB Имею коллекцию:
{
"_id" : ObjectId("5c7c804f14b4c026ba7fcaba"),

"values" : [
    {
        "active" : true,
        "id" : 30,
    },

    {
        "active" : true,
        "id" : 33,
    },
    {
        "active" : true,
        "id" : 34,
    },
    {
        "active" : true,
        "id" : 35,
    },
    {
        "active" : true,
        "id" : 36,
    }
]

}
Нужно получить результат:
{
"_id" : ObjectId("5c7c804f14b4c026ba7fcaba"),

"values" : [
    {
        "active" : true,
        "id" : 30,
    },
    {
        "active" : true,
        "id" : 34,
    },
    {
        "active" : true,
        "id" : 35,
    },
    {
        "active" : true,
        "id" : 36,
    }
]

}
то есть не выводить value.id = 33 в результате.
Можно это сделать не через агрегацию ..aggregate(), а через find()? Может какой то javascript код с условием можно прикрутить, что не value.id = 33?

A: Попробуйте так:
db.test.find( { 'value.id': { $ne: 33 } } )


text:
Q: Use Timber/Twig to pull an image by image ID Is it possible to use Twig to pull an image by ID, or only to pull the post.thumbnail? The Twig docs don't seem to cover any other image need and I'd like to specify a backup image in case no post.thumbnail is found.
I think what I need is something like wp_get_attachment_image_src(1234,'medium_16x9') but in Twig's language.

        {% if post.thumbnail %}

        {% else %}

        {% endif %}

I suppose I could set this up in the PHP by adding the backup image URL to a variable, but this means I'd have to add that code to every PHP file that calls this twig. It's better to grab the image in the twig, no?

A: {{ post.thumbnail.ID }} will get you the image ID, but to answer what you're after....

Reference


text:
Q: Dealing with missing values where the question was not asked I have a question about missing values. We used 3 versions of a questionnaire were the possible answers were numeric (0-10) with 0 = no pain and 10 = worst possible pain. We had 4 pain questions worst, least, average and pain now and only the first version of the questionnaire asked all 4 pain questions. I scored the data as 999 for truly missing values and 888 for missing values when the question was not asked. I want to create a 'total pain score'. I summing the scores of average and pain now. I divided the result by 2 if there are two valid values (e.g. 0 and 4 =2). If one sore was 888 treated this like a dummy variable and did not delete the paired value and did not divide by 2 (e.g. 888 and 2 =2). Does this sound like the appropriate way to deal with my missing values? -If I use pair wise deletion I lose 70% of my data.

A: So you have a sample of responses for 3 parallel versions of questionnaire, where some of the questions between versions are the same and you have one version where all the questions are present, correct?
For me, this sounds like an test equating problem. Consider that while you want the tests to be parallel, you do not know if people answered all the questions the same way. So there could be different response patterns for question 1 and question 4 and if so, then the same raw sum of scores on two tests consisting of different questions would mean different things. In this case you could employ test equating, that is, a statistical procedure that lets you to transform raw scores of one questionnaire into the scale of another, so that both tests share the same scale and are equivalent.
The simple example is linear equating, where if you want co transform raw score of questionnaire $X$ into scale of $Y$ you use mean and standard deviation:
$$Lin_Y(x) = \frac{\sigma_Y}{\sigma_X}x + \left( \mu_Y - \frac{\sigma_Y}{\sigma_X}\mu_X \right)  $$
there is also more advanced method that use cumulative distribution functions - the equipercentile equating method:
$$Equi_Y(x) = F^{-1}_Y \left[ F_X(x) \right]$$
However, the second method needs special data preparation beforehand i.e. continuization of the scores. Of course, there are also other methods as well.
Wile the questionnaires were answered by different populations, you could use the questions that are common between versions of questionnaires as anchor tests in equivalent groups design.
Check books on equating by Kolen and Brennan and von Davier at al for more informations.


text:
Q: Magento1.9 CSV generate but not download on save action Here is my controller code ::
public function saveAction()
        {
            $post_data=$this->getRequest()->getPost();
            if ($post_data) {

                try {
                    $orderId = 1;
                    $order = Mage::getModel("sales/order")->load($orderId);
                    $header = array('Order Id','Product Name','Sku','Price');
                    $io = new Varien_Io_File();
                    $path = Mage::getBaseDir('var') . DS . 'export' . DS;
                    $name = 'file-'.$orderId.'.csv';
                    $file = $path . DS . $name;
                    $io->setAllowCreateFolders(true);
                    $io->open(array('path' => $path));
                    $io->streamOpen($file, 'w+');
                    $io->streamLock(true);
                    $io->streamWriteCsv($header);

                    $items = $order->getAllItems();
                    foreach ($items as $item) {
                        $data = array($order->getIncrementId(), $item->getName(), $item->getSku(), $item->getPrice());
                        $io->streamWriteCsv($data);
                    }
                    $io->streamUnlock();
                    $io->streamClose();
                    // Download
                    $this->_prepareDownloadResponse($name, file_get_contents($file));
                    $this->_getSession()->addSuccess($this->__('File downloaded.'));
                }
                catch (Exception $e) {
                    Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
                    Mage::getSingleton("adminhtml/session")->setExampleData($this->getRequest()->getPost());
                    $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
                    return;
                }

            }
            $this->_redirect("*/*/");
        }

$this->_prepareDownloadResponse - Download function but not working direct redirect with success message but file not download.

A: Finally got issue. here is solution
1. you need to prepare array insted of `file_get_contents($file)`
like below
                      $csv = Array(
                            'type' => 'filename',
                            'value' => $file,
                            'rm' => '1'
                        );

2. change this function .

    old - $this->_prepareDownloadResponse($name, file_get_contents($file));
    new - $this->_prepareDownloadResponse($name, $csv);

Now it's works!!!!


text:
Q: ASP.Net ITemplate - ways of declaring when we want to define a Template in our user controls we declare a field like this in our user controls
public ITemplate MyTemplate { get; set; }

so that the user defined templates contents will be represented in MyTemplate, and you can use it.
and there are ways to customize the templates, for example
[TemplateInstanceAttribute(TemplateInstance.Single)]
public ITemplate MyTemplate { get; set; }

the above example will enable defines single instance Templates(http://www.nikhilk.net/SingleInstanceTemplates.aspx).
i accidentally came across single instance templates and blown away by the power of it.
my question is what are all the things possible with ITemplates?? how do we define(use) them (more specifically thru annotations). is there any good documentation available for ITemplates?? (please dont point to msdn)

A: It does look like you're declaring the template properly. To actually populate the contents with your own template, you declare it in your markup. Eg:
<MyControl runat="server" ...>
  <MyTemplate>
   ... any standard ASP.NET controls in here
   <asp:Label runat="server" ID="lblName"/>
  </MyTemplate>
</MyControl>

  public void InstantiateIn(Control container) {
      var lblName = container.FindControl("lblName") as Label;
      lblName.Text = "Blah";// set from your data layer or otherwise
      Button b = new Button();
      b.ID = "B";
      container.Controls.Add(b);
  }

Is this what you were looking for?


text:
Q: add an object in middle of the list based on the condition I am having a sorted list like below

with the below code I have sorted.
             Comparator<MyBean> typeComparator = Comparator.comparing(MyBean::getType);

             Comparator<MyBean> costComparator = Comparator.comparing(MyBean::getCost);

             Comparator<MyBean> multipleFieldsComparator = typeComparator.thenComparing(costComparator);

             Collections.sort(mbList, multipleFieldsComparator);

Now I am identifying the total cost of each Type with the below code.
Map<String, Double> sum = mbList.stream().collect(
                        Collectors.groupingBy(MyBean::getType, Collectors.summingDouble(MyBean::getCost)));

Here I am having total cost of each type. like A = 109490.03 and B = 4431.218
Now I need to add this Total Cost object in middle of the mbList list.
My desired output should be like below

My whole code is like below.
             Comparator<MyBean> typeComparator = Comparator.comparing(MyBean::getType);

             Comparator<MyBean> costComparator = Comparator.comparing(MyBean::getCost);

             Comparator<MyBean> multipleFieldsComparator = typeComparator.thenComparing(costComparator);

             Collections.sort(mbList, multipleFieldsComparator);

             Map<String, Double> sum = mbList.stream().collect(
                        Collectors.groupingBy(MyBean::getType, Collectors.summingDouble(MyBean::getCost)));
            System.out.println(" $$$$$$$$$$$$$$$$$ "+sum);

            for (MyBean mb : mbList) {

                row = sheetType.createRow(sheetType.getPhysicalNumberOfRows());
                cell = row.createCell(cellnum++);
                cell.setCellValue((String) mb.getType() + "-" + mb.getCategory());
                cell = row.createCell(cellnum++);
                cell.setCellValue(mb.getCost());
                cellnum = 0;
            }

MyBean.java
public class MyBean{
    private String type;
    private Double total;
    private String xxx;
    private String yyy;

    //setters and getters
}

Here my question is how can I add the Total cost at the end of each sorting value like After A Total cost needs to be added and After B we can add Total cost....

A: You're almost there, but instead of aggregating the sum directly, group by type first, and then calculate the sums for every sub-list:
a) group by type
Map<String, List<MyBean>> byType = mbList.stream()
                                         .sorted(multipleFieldsComparator)
                                         .collect(
                                             Collectors.groupingBy(
                                                 MyBean::getType,
                                                 LinkedHashMap::new, // preserves order
                                                 Collectors.toList()
                                             ));

b) calculate sum for each type
for (Entry<String, List<MyBean>> entry : byType.entrySet()) {
    List<MyBean> typeList = entry.getValue();
    double sum = typeList.stream().mapToDouble(MyBean::getCost).sum();
    typeList.add(new MyBean(entry.getKey(), sum));
}

c) flatten all the lists to one big list (they're already ordered correctly)
List<MyBean> listWithSums = byType.values()
                                  .stream()
                                  .flatMap(List::stream)
                                  .collect(Collectors.toList());

A: here is quick draft of idea, there must be better solution than this but this will do the trick (will update this answer later to improve the code)
lastMatch = "", totalCost = 0;
for ( mbList i = 0 -> n) {
    currentMatch = mbList[i].getType(); // return A- or B- ...
    if(currentMatch != lastMatch){
        if(lastMatch != ""){
            > print totalCost; // to avoid printing Total cost at first row
        }
        lastMatch = currentMatch;
        totalCost = 0;
    }
    > print col name = col value
    totalCost += mbList[i].getCost(); // keep adding cost for your currentRegExrMatch
}


text:
Q: types.ts enums is undefined I'm currently upgrading from webpack 3 to 5 using ruby on rails shakapacker gem which is the successor of webpacker (a wrapper around webpack)
I'm bumping into the issue that some of the enums I defined in my types.ts files are undefined when loading inside the browser.
Example:
Constants.ts
// Some source file
export const DEFAULT_LOCALE: Locale = Locale.EN;

types.ts
const enum Locale {
  EN = 'en',
  NL = 'nl',
  FR = 'fr',
  DE = 'de'
}

I see no typescript errors whatsoever. Loading the page results in this error being thrown.
It seems the enums are stripped for some reason, but I don't know what new configuration might have changed this.
This code works as expected on a previous version
Any help in the right direction would be greatly appreciated!
Kind regards
Jens


text:
Q: Tutorials on connected data access architecture of ADO.Net? http://www.programmersheaven.com/2/FAQ-ADONET
Disconnected architecture is not well suited for desktop clients with multiple updates but most tutorials are oriented towards disconnected ado.net would like to see tuts on connected data access architecture.
So any links ?
Thanks.

A: I've written an ADO.NET tutorial that discusses connected operations:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
Joe


text:
Q: Get type from variant at compile time I need to do a typecheck on whether a variant type can hold a type at compile time.
I am converting an enum and a string to a variant, but I want the library to be compatible with a user provided variant (for the types they support). So I have a template parameter CustomVariant to represent a variant over a subset of the supported types, AlphaBeta, Gamma, Delta, and Epsilon. I would like to return std::nullopt if I can't create a valid variant.
template <typename CustomVariant>
std::optional<CustomVariant> AsCustomVariant(LargeEnum type, const std::string& name) {
  case LargeEnum::ALPHA:
  case LargeEnum::BETA:
    return ConvertAlphaBeta(name);

  case LargeEnum::GAMMA:
    return ConvertGamma(name);

  case LargeEnum::DELTA:
    return ConvertDelta(name);

  case LargeEnum::EPSILON:
    return ConvertEpsilon(name);

  default:
    return std::nullopt;
}

The idea is to use some sort of template magic that can do something like:
if (std::type_can_convert<CustomVariant, Gamma>) {
  return ConvertGamma(name);
} else {
  return std::nullopt;
}

A: With c++17 (I know it's tagged with c++11), this is super easy - you don't even have to really do anything:
#include <variant>
#include <type_traits>
#include <string>

using namespace std;

int main() {

    // this works, as expected
    if constexpr(is_constructible_v<variant<int>, double>) {
        // this will run
    }

    // this is fine - it just won't happen,
    if constexpr(is_constructible_v<variant<int>, string>) {
        // this won't run
    } else {
        // this will run
    }
    // but obviously the assignment of a string into that variant doesn't work...
    variant<int> vi="asdf"s;
}

https://godbolt.org/z/I-wJU1

A: First I'd do this:
template<class T>struct tag_t{using type=T;};
template<class T>constexpr tag_t<T> tag{};

template<class...Ts>using one_tag_of=std::variant<tag_t<Ts>...>;

using which_type=one_tag_of<AlphaBeta, Gamma, Delta /* etc */>;

which_type GetType(LargeEnum e){
  switch (e){
    case LargeEnum::Alpha:
    case LargeEnum::Beta: return tag<AlphaBeta>;
    // etc
  }
}

Now we do this:
template <typename CustomVariant>
std::optional<CustomVariant> AsCustomVariant(LargeEnum type, const std::string& name) {
  auto which = GetType(type);
  return std::visit( [&name](auto tag)->std::optional<CustomVariant>{
    using type=typename decltype(tag)::type;
    if constexpr (std::is_convertible<CustomVariant, type>{})
      return MakeFromString( tag, name );
    return std::nullopt;
  }, which );
}

this leaves MakeFromString.
Write overloads like this:
inline Delta MakeFromString(tag_t<Delta>, std::string const& name){ return ConvertDelta(name); }

note, not specializations.  Just overloads.


text:
Q: Invalid Argument Error: No OppKernel was registered to support Op 'CudnnRNNV2' Trying to run a machine learning code and wound up getting the error below when running the last section of the code. The error pops up not only in the last section of the code but also the section before it (Training), only after running the Prediction section.
When I originally downloaded the code from the web, it would not run at all. After some troubleshooting, I found a suggestion to load Microsoft Visual C++ 2015-2019 Redistributable (x86). This allowed me to run most of the code. How do I fix this error?
'''
# Training

model.compile(
    loss='mean_squared_error',
    optimizer='adam'
)

BATCH_SIZE = 64

history = model.fit(
    X_train,
    y_train,
    epochs=50,
    batch_size=BATCH_SIZE,
    shuffle=False,
    validation_split=0.1
)

model.evaluate(X_test, y_test)

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

Epoch 1/50

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-8-16bf71f53dfc> in <module>
      8 BATCH_SIZE = 64
      9
---> 10 history = model.fit(
     11     X_train,
     12     y_train,

~\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1098                 _r=1):
   1099               callbacks.on_train_batch_begin(step)
-> 1100               tmp_logs = self.train_function(iterator)
   1101               if data_handler.should_sync:
   1102                 context.async_wait()

~\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

~\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    886         # Lifting succeeded, so variables are initialized and we can run the
    887         # stateless function.
--> 888         return self._stateless_fn(*args, **kwds)
    889     else:
    890       _, _, _, filtered_flat_args = \

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in __call__(self, *args, **kwargs)
   2940       (graph_function,
   2941        filtered_flat_args) = self._maybe_define_function(args, kwargs)
-> 2942     return graph_function._call_flat(
   2943         filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access
   2944

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1916         and executing_eagerly):
   1917       # No tape is watching; skip to running the function.
-> 1918       return self._build_call_outputs(self._inference_function.call(
   1919           ctx, args, cancellation_manager=cancellation_manager))
   1920     forward_backward = self._select_forward_and_backward_functions(

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    553       with _InterpolateFunctionError(self):
    554         if cancellation_manager is None:
--> 555           outputs = execute.execute(
    556               str(self.signature.name),
    557               num_outputs=self._num_outputs,

~\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     57   try:
     58     ctx.ensure_initialized()
---> 59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:

InvalidArgumentError: No OpKernel was registered to support Op 'CudnnRNNV2' used by {{node sequential/bidirectional/forward_cu_dnnlstm/CudnnRNNV2}} with these attrs: [seed=0, dropout=0, T=DT_FLOAT, input_mode="linear_input", direction="unidirectional", rnn_mode="lstm", seed2=0, is_training=true]
Registered devices: [CPU]
Registered kernels:
  device='GPU'; T in [DT_HALF]
  device='GPU'; T in [DT_FLOAT]
  device='GPU'; T in [DT_DOUBLE]

     [[sequential/bidirectional/forward_cu_dnnlstm/CudnnRNNV2]] [Op:__inference_train_function_5956]

# Prediction

y_hat = model.predict(X_test)

y_test_inverse = scaler.inverse_transform(y_test)
y_hat_inverse = scaler.inverse_transform(y_hat)

plt.plot(y_test_inverse, label="Actual Price", color='green')
plt.plot(y_hat_inverse, label="Predicted Price", color='red')

plt.title('Bitcoin price prediction')
plt.xlabel('Time [days]')
plt.ylabel('Price')
plt.legend(loc='best')

plt.show();

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-28-b81bf8d6b99c> in <module>
      1 # Prediction
      2
----> 3 y_hat = model.predict(X_test)
      4
      5 y_test_inverse = scaler.inverse_transform(y_test)

~\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   1627           for step in data_handler.steps():
   1628             callbacks.on_predict_batch_begin(step)
-> 1629             tmp_batch_outputs = self.predict_function(iterator)
   1630             if data_handler.should_sync:
   1631               context.async_wait()

~\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

~\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    892               *args, **kwds)
    893       # If we did not create any variables the trace we have is good enough.
--> 894       return self._concrete_stateful_fn._call_flat(
    895           filtered_flat_args, self._concrete_stateful_fn.captured_inputs)  # pylint: disable=protected-access
    896

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1916         and executing_eagerly):
   1917       # No tape is watching; skip to running the function.
-> 1918       return self._build_call_outputs(self._inference_function.call(
   1919           ctx, args, cancellation_manager=cancellation_manager))
   1920     forward_backward = self._select_forward_and_backward_functions(

~\anaconda3\lib\site-packages\tensorflow\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    553       with _InterpolateFunctionError(self):
    554         if cancellation_manager is None:
--> 555           outputs = execute.execute(
    556               str(self.signature.name),
    557               num_outputs=self._num_outputs,

~\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     57   try:
     58     ctx.ensure_initialized()
---> 59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:

InvalidArgumentError: No OpKernel was registered to support Op 'CudnnRNNV2' used by {{node sequential_1/bidirectional_3/forward_cu_dnnlstm_3/CudnnRNNV2}} with these attrs: [seed=0, dropout=0, T=DT_FLOAT, input_mode="linear_input", direction="unidirectional", rnn_mode="lstm", seed2=0, is_training=true]
Registered devices: [CPU]
Registered kernels:
  device='GPU'; T in [DT_HALF]
  device='GPU'; T in [DT_FLOAT]
  device='GPU'; T in [DT_DOUBLE]

     [[sequential_1/bidirectional_3/forward_cu_dnnlstm_3/CudnnRNNV2]] [Op:__inference_predict_function_13727]

'''


text:
Q: EXCEL sumproduct formula not counting correctly I have a formula in EXCEL 2013 that counts values where the decimal point = .16
=SUMPRODUCT(--(MOD(D2:D9,1)=0.16))

so for example 2.16, 15.16  will be a count of 2. However if the value is 32.16 or greater then will not count. This is very weird issue and cannot fathom this out.

A: You've hit a floating point error¹. The remainder reads as 0.159999999999997, not 0.16. Round it to at least four decimals to get an accurate read.
=SUMPRODUCT(--(ROUND(MOD(D2:D9,1), 4)=0.16))

¹ See 15 digit precision floating point errors and Floating-point arithmetic may give inaccurate results in Excel.


text:
Q: Instagram Data For Python Facebook API I tried accessing Instagram post reach based on the Instagram post ID found via the Graph API
impressions= graph.get_object(id='17881493329146188', fields='reach')

I am getting the following error:
GraphAPIError: (#100) Tried accessing nonexisting field (reach) on node type (ShadowIGMedia)

Is there any way to successfully retrieve reach on Instagram posts through this Facebook API Python wrapper?

A: Reach isn't a field on media, but on the insights under the object. You could do:
impressions = graph.get_object(id='17881493329146188', fields='insights.metric(reach)')

Depending on what type of object that is, you may need to specify period and other fields, e.g. fields='insights.metric(reach).period(lifetime)'


text:
Q: VBA: Primary key on ADODB.Recordset from query on Excel worksheet I am working on a VBA routine that retrieves data from an Excel workbook, does some simple processing (turns string into upper case, removes spaces from the left and right ends, calculates codes, etc.) and creates a .csv file to be imported into the company's ERP via an embedded functionality. To do this I retrieve the data from the worksheet with an SQL-like query that opens an ADODB recordset, then I iterate through it modifying the field values and finally update the recordset, like this:
Private sub rsOps(ByRef cnn As ADODB.Connection, ByRef rs As ADODB.Recordset, ByRef wsOr As Worksheet)
Dim strSQL As String
rs.CursorLocation = adUseClientBatch
strSQL = "Select ROWID, {...some fields...}, ltrim(rtrim(Description)) as Descr, " _
        & "{...other fields...} " _
        & "From [" & wsOr.Name & "$]"
rs.Open strSQL, cnn, adOpenKeyset, adLockBatchOptimistic
With rs
    If Not .BOF And Not .EOF Then   'Check if there are any records
        .MoveLast
        .MoveFirst
        While Not .EOF
            '{further data processing}
            .MoveNext
        Wend
        .UpdateBatch
    End If
End With

The problem is on ltrim(rtrim(Description)) and this makes the rs.UpdateBatch command to fail because it cannot retrieve the starting references anymore:

Error -2147217864 (80040e38). Row cannot be located for updating. Some values may have been changed since it was last read.

Is it possible to enforce a primary key? My ROWID never changes so that could do the job, but I don't know how to set it.
Edit: The failure does not occur on either of these cases:

*

*Application of ltrim(rtrim(Descr)) while looping through the recordset rather than directly on the starting query

*The starting data does not contain any spaces at the start/end of the string (so it's unmodified by the query)


text:
Q: White Line Appears when using backface-visibility to make css transition effect to zoom image on hover Im facing a difficulty to figure out some small CSS issue causing it seems with backface-visibility property that it shows a white line right of the image of 2nd item in each row in a grid. Im here giving u link to html i have done so far. But cant figure out why it is showing this white line. Any help would be highly appreciated.
Here is the link - http://s194142.gridserver.com/webtest/
FYI - I see this line i both chrome and FF. Not tested in other browsers.

A: style.css 163
#posts .col.span_sm_4 .post-content - remove - background-color: #fff;
style.css 170
#posts .col.span_sm_4 .post-meta - add - background-color: #fff;


text:
Q: Asp.Net using dll with web application project i am developing an asp.net web application project.i have add a dll file with add reference command but i get error when i have  said it Using namespace_name.
Note : i tried as Asp.Net Web site.But problem is continue.i checked framework version.
C# :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DenemePc; <-- dll file

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

ERROR:
'DenemePc' The type or namespace name could be found (are you missing a using directive or assembly reference?)

A: I believe I have answered a similar question ASP.NET => Compiler Error Message: CS0246: The type or namespace name 'HtmlAgilityPack'
Please set the Copy Local property to True on the Referenced DLL of DenemePc
This will copy the dll to the output directory of your application


text:
Q: Create keyboard shortcut in Arch [gnome] Im new to Arch and just installed it with gnome as a DE. I can run the gnome shell by clicking the icon but would like to setup a shortcut for it.
I'd like to setup the shortcut like in Ubuntu, Ctrl + Alt + T.
Does anyone have any sujestions or can point me in the right direction?
Edit:
I found you can ad a shortcut through Settings>Keyboard>View and Customise Shortcuts. It asks for a command. What would would that command be? I'm trying to get it to open up at /home.

A: Answer found Here: How to run the terminal using keyboard shortcuts in Gnome 2?
Command is gnome-terminal &


text:
Q: Storing integer to QByteArray using only 4 bytes It takes 4 bytes to represent an integer. How can I store an int in a QByteArray so that it only takes 4 bytes?

*

*QByteArray::number(..) converts the integer to string thus taking up more than 4 bytes.

*QByteArray((const char*)&myInteger,sizeof(int)) also doesn't seem to work.

A: There are several ways to place an integer into a QByteArray, but the following is usually the cleanest:
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);

stream << myInteger;

This has the advantage of allowing you to write several integers (or other data types) to the byte array fairly conveniently.  It also allows you to set the endianness of the data using QDataStream::setByteOrder.
Update
While the solution above will work, the method used by QDataStream to store integers can change in future versions of Qt.  The simplest way to ensure that it always works is to explicitly set the version of the data format used by QDataStream:
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_5_10); // Or use earlier version

Alternately, you can avoid using QDataStream altogether and use a QBuffer:
#include <QBuffer>
#include <QByteArray>
#include <QtEndian>

...

QByteArray byteArray;
QBuffer buffer(&byteArray);
buffer.open(QIODevice::WriteOnly);
myInteger = qToBigEndian(myInteger); // Or qToLittleEndian, if necessary.
buffer.write((char*)&myInteger, sizeof(qint32));

A: @Primož Kralj did not get around to posting a solution with his second method, so here it is:
int myInt = 0xdeadbeef;
QByteArray qba(reinterpret_cast<const char *>(&myInt), sizeof(int));

qDebug("QByteArray has bytes %s", qPrintable(qba.toHex(' ')));

prints:
QByteArray has bytes ef be ad de

on an x64 machine.

A: Recently I faced the same problem with a little variation. I had to store a vector of unsigned short into QByteArray. The trick with QDataStream did not work for unknown reason. So, my solution is:
QVector<uint16_t> d={1,2,3,4,5};
QByteArray dd((char*)d.data(),d.size()*sizeof(uint16_t));

The way to get the vector back is:
QVector<uint16_t> D;
for(int i=0; i<dd.size()/sizeof(uint16_t); ++i){
  D.push_back(*(uint16_t*)(dd.data()+i*sizeof(uint16_t)) );
}


text:
Q: AWS RDS snapshot sharing takes too long I've shared a RDS manual snapshot between two accounts that I have. And after an hour I still can't see it in the other account.
How long does this normally take?

A: Apparently, for a 1TB DB size. This could take hours. Or not work at all.
My only tip would be to first copy to the region you want to share with and then share from there.
AWS said it's suppose to be really fast since data is not actually copied. So they said.


text:
Q: Jquery trigger enter and clicked button functionality on form I am working on a form and in that form button is disabled by starting and after filling the form button will get able to submit it. Now, I want that after filling the form the user should be able to submit the form by clicking enter button as well and it should validate if the all the fields are filled or not as well. I want this functionality with Jquery only.
Thanks in advance.
Here is the code on which I want this to be:-

        <title></title>

    Website - (Optional Field)
    <input class="form-control" id="URL" placeholder="www.example.com" type="url">

    Name
    <input class="form-control" id="Legal_Name" placeholder="Enter Your Legal Name" type="text">

 Doing As - (Common Name)
    <input class="form-control" id="Doing" type="email">

    <button type="submit" class="btn btn-default section_btn section-5-next hover_ease btn_disable">Next</button>

A: You can do like this using jquery:

A: Check this Submit form with Enter key without submit button?
$("input").keypress(function(e) {
    if (e.which == 13) {
        event.preventDefault();
        $("#formtosubmit").submit();
    }
});


text:
Q: Compare two columns from which one column is not mandatory I need help for a macro code.
In my case the excel macro checks data in one sheet ("Check_file") for completeness and correctness.
There are mandatory columns in the sheet which have to exist and also not-mandatory columns can exist.
In my example the columns "company" and "fee" are mandatory columns, if they are missing or false the macro will throw an error.
Next to them, the column "gross fee" is not-mandatory and its data should only be checked with the data in column "fee", if column "gross fee" exists. If it exists, the amount should be the same as in column "fee". If it doesnt exist, there should be no comparison.
The check for the mandatory columns works fine within a For-Loop and an own Range.
My problem is that I dont know how I can involve the not-mandatory columns into the loop of the mandatory columns…
I tried to define a separate Range for the not-mandatory columns area. But it seems that I cannnot create the connection to the not-mandatory column if it is not set in the mandatory columns loop. But if it is set to the mandatory columns range and the not-mandatory column doesnt exist, an error will be thrown.
Should the exist-check for the not-mandatory columns be placed in a separate Sub or Function? If yes, how can the connection be created to the mandatory check Range?
This is the vba code:
Function Main_Check(ByVal StrFilePath As String) As String
    '//Checks all criteria for the correct filling of the template. Marks all fields that are incorrectly
    filled in red.

    Dim WB As Workbook, WS As Worksheet
    Dim i As Long, iNotMand As Long, lEnde As Long, strHeader As String, ii As Long, lColEnde As Long
    Dim rngFind As Range, booCheck As Boolean, rngHeader As Range, rngKey As Range, rngUsed As Range,
    rngHeaderNotMand As Range, rngFindNotMand As Range, rngKeyGrossFee As Range, rngGrossFee As Range
    Dim strKey As String, arrKey As String, strKeyGrossFee As String, strGrossFee As String

    On Error GoTo ErrorHandler

    If StrFilePath = "" Then GoTo ErrorHandler

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    '//Template is opened
    Set WB = Workbooks.Open(StrFilePath)
    Set WS = WB.Worksheets("Check_file")

    With WS
    .Cells.EntireColumn.AutoFit

    '//Stores the last row and column to be processed
    lEnde = .Cells(.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 2, 2).End(xlUp).Row
    lColEnde = .UsedRange.SpecialCells(xlCellTypeLastCell).Column

    '//Find the beginning of the table
    Set rngFind = .Cells.Find(what:=Settings.Cells(Settings.Range("Header_Start").Row + 1, 2).Value,
    LookIn:=xlValues, lookat:=xlWhole)
    If rngFind Is Nothing Then
         booCheck = False
    End
    End If

    .Range(rngFind.Address, .Cells(.UsedRange.SpecialCells(xlCellTypeLastCell).Row,
    rngFind.Column)).EntireRow.Hidden = False

    lEnde = .Cells(.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 2, 2).End(xlUp).Row

    '//booCheck is set to true and on error to false _
    Thus, if "True" is passed, the complete file is correct

    Set rngUsed = .Range(rngFind.Address, .Cells(lEnde, lColEnde))

    booCheck = IsErrorAll(rngUsed)

    '//Header Check _
    Checks all headers in advance to see if they are present and writes the missing ones in a cell
    .Cells(4, 7).Clear
    .Cells(4, 8).Clear
     For i = Settings.Range("Header_Start").Row + 1 To Settings.Range("Header_Ende").Row - 1
    Set rngHeader = .Range(rngFind, .Cells(rngFind.Row, lColEnde)).Find(what:=Settings.Cells(i, 2).Value,
    LookIn:=xlValues, lookat:=xlWhole)
        If rngHeader Is Nothing Then
             booCheck = False

             .Cells(4, 7).Value = "The following column labels were not found: "

             If .Cells(4, 8).Value = "" Then
                  .Cells(4, 8).Value = .Cells(4, 8).Value & Settings.Cells(i, 2).Value
             Else
                  .Cells(4, 8).Value = "," & .Cells(4, 8).Value & Settings.Cells(i, 2).Value
             End If
             .Cells(4, 8).Interior.Color = vbRed

         Else

         End If

Next i

    If booCheck = False Then GoTo Ende

    '// Check Not-Mandatory Columns _
     Checks in advance whether Not-mandatory columns are available
    Set rngFindNotMand = .Cells.Find(what:=Settings.Cells(Settings.Range("NotMand_Start").Row + 1, 2).Value, LookIn:=xlValues, lookat:=xlWhole)
For iNotMand = Settings.Range("NotMand_Start").Row + 1 To Settings.Range("NotMand_Ende").Row - 1
Set rngHeaderNotMand = .Range(rngFindNotMand, .Cells(rngFindNotMand.Row, lColEnde)).Find(what:=Settings.Cells(iNotMand, 2).Value, LookIn:=xlValues, lookat:=xlWhole)
    If Not rngHeaderNotMand Is Nothing Then
    '//Not-mandatory columns are defined
     strKeyGrossFee = "Gross fee"
     Set rngKeyGrossFee = Settings.Cells(1, 1).EntireColumn.Find(what:=strKeyGrossFee, LookIn:=xlValues, lookat:=xlWhole)
     strGrossFee = Settings.Cells(rngKeyGrossFee.Row, 2).Value
    Else
    strKeyGrossFee = ""
    End If

'//All line items are run through and the individual criteria are checked
For i = rngFind.Row + 1 To lEnde Step 1

    '//Company
    strKey = "Company"
    Set rngKey = Settings.Cells(1, 1).EntireColumn.Find(what:=strKey, LookIn:=xlValues, lookat:=xlWhole)
    strHeader = Settings.Cells(rngKey.Row, 2).Value
    Set rngHeader = .Range(rngFind, .Cells(rngFind.Row, lColEnde)).Find(what:=strHeader, LookIn:=xlValues, lookat:=xlWhole)
    iCoi = rngHeader.Column
    If .Cells(i, rngHeader.Column).Value Like "####" Then
        .Cells(i, rngHeader.Column).Interior.Pattern = xlNone
    Else
        .Cells(i, rngHeader.Column).Interior.Color = vbRed
        booCheck = False
    End If

    '//Fee
    strKey = "Fee"
    Set rngKey = Settings.Cells(1, 1).EntireColumn.Find(what:=strKey, LookIn:=xlValues, lookat:=xlWhole)
    strHeader = Settings.Cells(rngKey.Row, 2).Value
    Set rngHeader = .Range(rngFind, .Cells(rngFind.Row, lColEnde)).Find(what:=strHeader, LookIn:=xlValues, lookat:=xlWhole)
    If .Cells(i, rngHeader.Column).Value Like "*,*" Then
             .Cells(i, rngHeader.Column).Interior.Color = vbRed
              booCheck = False
    Else
        .Cells(i, rngHeader.Column).Interior.Pattern = xlNone
    End If

    '//Gross fee
    strKey = "Fee"
    Set rngKey = Settings.Cells(1, 1).EntireColumn.Find(what:=strKey, LookIn:=xlValues, lookat:=xlWhole)
    strHeader = Settings.Cells(rngKey.Row, 2).Value
    Set rngHeader = .Range(rngFind, .Cells(rngFind.Row, lColEnde)).Find(what:=strHeader, LookIn:=xlValues, lookat:=xlWhole)

    Set rngFindNotMand = .Cells.Find(what:=Settings.Cells(Settings.Range("NotMand_Start").Row + 1, 2).Value, LookIn:=xlValues, lookat:=xlWhole)
    strKeyGrossFee = "Gross fee"
    Set rngKeyGrossFee = Settings.Cells(1, 1).EntireColumn.Find(what:=strKeyGrossFee, LookIn:=xlValues, lookat:=xlWhole)
    strGrossFee = Settings.Cells(rngKeyGrossFee.Row, 2).Value
    Set rngGrossFee = .Range(rngFindNotMand, .Cells(rngFindNotMand.Row, lColEnde)).Find(what:=strGrossFee, LookIn:=xlValues, lookat:=xlWhole)

    If .Cells(i, rngGrossFee.Column).Value Is Nothing Then
       .Cells(i, rngHeader.Column).Interior.Pattern = xlNone
    ElseIf .Cells(i, rngHeader.Column).Value <> .Cells(i, rngGrossFee.Column).Value Then
       .Cells(i, rngHeader.Column).Interior.Color = vbRed
           booCheck = False
    Else
       .Cells(i, rngHeader.Column).Interior.Pattern = xlNone
    End If

Next i

End With

'//Define results
Ende:

Main_Check = booCheck & "," & Replace(CStr(rngFind.Address), "$", "")

If booCheck = False Then
WS.Cells(7, 7).Value = "Error counter:"
WS.Cells(7, 8).Value = WS.Cells(7, 8).Value + 1
Else
WS.Cells(7, 7).Value = "Check ok"
WS.Cells(7, 8).Value = ""
End If

WB.Close (True)

With Application
.ScreenUpdating = True
.EnableEvents = True
End With

Exit Function

'//If there are other errors, it should exit here and return ERROR
ErrorHandler:
On Error GoTo -1
On Error Resume Next
Main_Check = "ERROR"
WB.Close (True)

With Application
.ScreenUpdating = True
.EnableEvents = True
End With

End Function

A: I would recommend you refactor your code into 3 parts. 1- read the settings, 2- profile the sheet and then 3- check the data. Debug each step in turn.
Function Main_Check2(ByVal StrFilePath As String) As String

    Const CHECK = "Check_file"

    Dim wb As Workbook, ws As Worksheet, arHdr
    Dim booCheck As Boolean, bExists As Boolean
    Dim iColFee As Long, i As Long, msg As String

     ' check valid filepath
    If Dir(StrFilePath) = "" Then
        msg = "'" & StrFilePath & "' does not exist"
        MsgBox msg, vbCritical, "File not found"
        Main_Check2 = msg
        Exit Function
    End If

     ' open file and check sheet exists
    Set wb = Workbooks.Open(StrFilePath)
    bExists = False
    For Each ws In wb.Sheets
        If ws.Name = CHECK Then
            bExists = True
            Exit For
        End If
    Next

    If Not bExists Then
        msg = "Sheet '" & CHECK & "' not found in " & wb.FullName
        MsgBox msg, vbCritical, "Sheet not found"
        wb.Close False
        Exit Function
    End If

    ' get header details from settings sheet
    Call GetSettings(Settings, arHdr)

    ' check headers, find fee column
    booCheck = CheckHeaders(ws, arHdr, iColFee)
    'Call DumpArray(arHdr) ' check results so far

    ' exit if false
    If booCheck = False Then
         Main_Check2 = booCheck
         Exit Function
    End If

    ' check data
    With ws

        '//All line items are run through and the individual criteria are checked
        Dim rngData As Range, sName As String, n As Long
        Dim iRow As Long, iCol As Long, lastrow As Long, cell As Range

        For i = 1 To UBound(arHdr)

            sName = arHdr(i, 1) ' header name
            iCol = arHdr(i, 4) ' header column
            iRow = arHdr(i, 5) ' header row
            n = arHdr(i, 6) ' number of rows

            ' scan column
            If iCol > 0 And n > 0 Then
                Set rngData = .Cells(iRow + 1, iCol).Resize(n)
                Select Case sName
                    Case "Company"
                        For Each cell In rngData
                            If cell.Value Like "####" Then
                               cell.Interior.Pattern = xlNone
                            Else
                               cell.Interior.Color = vbRed
                               booCheck = False
                            End If
                        Next

                    Case "Fee"
                        For Each cell In rngData
                            If Not cell.Value Like "*,*" Then
                               cell.Interior.Pattern = xlNone
                            Else
                               cell.Interior.Color = vbRed
                               booCheck = False
                            End If
                        Next

                    Case "Gross Fee"
                        ' optional - skipped if icol = 0
                        For Each cell In rngData
                            If Len(cell) = 0 Then
                                cell.Interior.Pattern = xlNone
                            ElseIf cell.Value <> .Cells(cell.Row, iColFee).Value Then
                                cell.Interior.Color = vbRed
                                booCheck = False
                            Else
                                cell.Interior.Pattern = xlNone
                            End If
                        Next
                End Select
            End If
        Next
    End With

'//Define results
Ende:
    If booCheck = False Then
        ws.Cells(7, 7).Value = "Error counter:"
        ws.Cells(7, 8).Value = ws.Cells(7, 8).Value + 1
    Else
        ws.Cells(7, 7).Value = "Check ok"""
        ws.Cells(7, 8).Value = ""
    End If

    'wb.Close True
    Main_Check2 = booCheck '& "," & Replace(CStr(rngFind.Address), "$", "")

End Function

Function GetSettings(ws, ByRef arHdr) As Boolean

    Dim r1 As Long, r2 As Long, r3 As Long, r4 As Long
    Dim n As Long, m As Long, i As Long, msg As String

    With ws
        r1 = .Range("Header_Start").Row
        r2 = .Range("Header_Ende").Row
        r3 = .Range("NotMand_Start").Row
        r4 = .Range("NotMand_Ende").Row

        m = r2 - r1 - 1 ' mandatory header
        n = r4 - r3 - 1 ' non-mandatory headers

        If m < 1 Then
            msg = "No mandatory headers on setting"
            MsgBox msg, vbExclamation, "Settings Error"
            getSettings = False
        End If

        ' size array and fill
        ReDim arHdr(1 To n + m, 1 To 6)
        For i = 1 To m
            arHdr(i, 1) = .Cells(r1 + i, 1)
            arHdr(i, 2) = .Cells(r1 + i, 2) ' search term
            If Len(arHdr(i, 2)) > 0 Then ' skip blanks
                arHdr(i, 3) = True ' mandatory
            Else
                arHdr(i, 3) = False
            End If
        Next
        For i = 1 To n
            arHdr(m + i, 1) = .Cells(r3 + i, 1)
            arHdr(m + i, 2) = .Cells(r3 + i, 2)
            arHdr(m + i, 3) = False ' optional
        Next

    End With
    getSettings = True

End Function

Function CheckHeaders(ws, ByRef arHdr, ByRef iColFee) As Boolean

    '//Header Check
    'Checks all headers in advance to see if they are present
    'and writes the missing ones in a cell
    Dim rngTable As Range, rng As Range
    Dim msg As String, sHdr As String, sTableStart As String
    Dim i As Long, lastrow As Long, rowHdr As Long
    Dim booCheck As Boolean

    ' search value for column 1 of table
    sTableStart = arHdr(1, 2)
    With ws
         '//Find the beginning of the table
        Set rngTable = .Cells.Find(what:=sTableStart, LookIn:=xlValues, lookat:=xlWhole)
        If rngTable Is Nothing Then
            msg = "Could not find begining of table '" & sTableStart & "'"
            MsgBox msg, vbExclamation, "Error"
            CheckHeaders = False
            Exit Function
        Else
            rowHdr = rngTable.Row
        End If

        For i = 1 To UBound(arHdr)
            sHdr = Trim(arHdr(i, 2))
            If Len(sHdr) > 0 Then ' skip blanks
                Set rng = .Rows(rowHdr).Find(what:=sHdr, LookIn:=xlValues, lookat:=xlWhole)
                If rng Is Nothing Then
                    arHdr(i, 4) = 0
                Else
                    ' store fee column for later gross fee check
                    If arHdr(i, 1) = "Fee" Then iColFee = rng.Column
                    arHdr(i, 4) = rng.Column
                    arHdr(i, 5) = rng.Row
                    lastrow = .Cells(.Rows.Count, rng.Column).End(xlUp).Row
                    arHdr(i, 6) = lastrow - rng.Row - 1 ' data rows
                End If
            Else
                arHdr(i, 4) = 0
            End If
        Next

        ' check for mandatory column errors
        Dim sep As String
        For i = 1 To UBound(arHdr)
            If arHdr(i, 3) And arHdr(i, 4) = 0 Then
                msg = msg & sep & arHdr(i, 2)
                sep = ","
            End If
        Next

        If Len(msg) > 0 Then
            .Cells(4, 7) = "The following column labels were not found: "
            .Cells(4, 8) = msg
            .Cells(4, 8).Interior.Color = vbRed
            CheckHeaders = False
            'GoTo Ende
        Else
            .Cells(4, 7).Clear ' G4
            .Cells(4, 8).Clear ' H4
            CheckHeaders = True
        End If
    End With

End Function

' dump array to new workbook to  debug
Sub DumpArray(ar)
    Dim wb As Workbook: Set wb = Workbooks.Add
    With wb.Sheets(1)
       .Name = "arHdr"
       .Range("A1:F1") = Array("Header1", "Header2", "Mandatory", "Column", "Row", "DataRows")
       .Range("A2").Resize(UBound(ar), UBound(ar, 2)) = ar
    End With
    ' save - replace existing
    Application.DisplayAlerts = False
    wb.SaveAs "debug_arHdr.xlsx"
    Application.DisplayAlerts = True
    'wb.Close
End Sub


text:
Q: Thread queue is full - python I have a code that use threading in python. each thread if met a condition will create 2 new threads. now problem is total number of active threads exceeds total number of active threads supported by ubuntu 12.04. now each thread in active thread queue need space to create new threads and then it will terminate. My system have 8 CPUs. now my code is going in deadlock.

A: You probably shouldn't create so many threads. Instead, use Queue.Queues to communicate between different threads.


text:
Q: How to export all tables in a PostgreSQL database to csv files? I went to the psql commandline mode and entered the correct database and I can list all the tables.
Now, I tried the following commands:
copy some_table_name1 to '/var/lib/pgsql/csv_exports/some_table_name1.csv' csv header
copy some_table_name2 to '/var/lib/pgsql/csv_exports/some_table_name2.csv' csv header

And so on...
There was no error messages or anything after the commands and I used tab-button to ensure that I was always referring to correct table names.
After doing this to all the tables I went to the directory and there were no files at all.
Am I doing something wrong?
EDIT: I should clarify that I was looking to that directory, by using putty and WINSCP, on the server machine. The same where I ran the psql commands in.

A: The files are written to that directory on the server machine, not the client.
Use COPY ... TO STDOUT to send the data to the client.

A: Using psql in the console you can use the following command to get your data in the client machine:
$ psql yourdb -c "COPY yourtable TO STDOUT DELIMITER ',' CSV HEADER" > output.csv
If you're wondering about how to do the other way around (import), take a look at this question.

A: Assuming that what you really want to do is to output the file to someplace on your local machine (ie your developer workstation), I suggest that you use the "\copy" command, instead of the "COPY" command.
psql -c "\copy (SELECT * FROM account) to '/tmp/account.csv' with csv;"

or
psql -c "\copy account TO '/tmp/account.csv' DELIMITER ',' CSV HEADER;

Otherwise, unless you explicitly redirect the command to stdout, as @LaurenzAlbe suggested, the "COPY"command will check and see if you are authorized to write the files out to the actual database server.  Normally, this is not the behavior that you and, and it requires accesses and permissions greater than most developers have.


text:
Q: Wordpress Syntax Error, unexpected [ I have a problem with a wordpress installation. When I work locally, this function works properly:
function get_images_from_media_library() {
  $args = array(
    'post_type' => 'attachment',
    'post_mime_type' =>'image',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => null, // any parent
    );
  $attachments = get_posts($args);
  $images = array();
  if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        array_push($images, wp_get_attachment_image_src($post->ID, 'full')[0]);
    }
  }
  return $images;
}

This retrieves all the images attached to media on the installation and returns them in an array.
However, when I put my installation up on my remote site, I get this error when I try to use the theme that holds this function:
Parse error: syntax error, unexpected '[' in /hermes/bosoraweb133/b2623/ipg.yourdomaincom/98EMcBee/wp-content/themes/98emcbee/functions.php on line 52

Line 52 is this line inside the foreach:
array_push($images, wp_get_attachment_image_src($post->ID, 'full')[0]);

Why would I get this error on a remote site and not on a local site?

A: That because you are using array dereferencing which is only available in PHP 5.4 and newer. You are using PHP 5.3 or older.
$array = wp_get_attachment_image_src($post->ID, 'full');
array_push($images, $array[0]);


text:
Q: Pandas: average over duplicate index values in DataFrame Say I have the following DataFrame:
df = pd.DataFrame({'a':[0,1,2,3,1,2,3,4],
                   'b':[4,4,2,4,6,7,8,9]},
                   index = ['2010Q1', '2010Q1', '2010Q2', '2010Q2', '2010Q2',
                            '2010Q3', '2010Q3', '2010Q4'])

        a  b
2010Q1  0  4
2010Q1  1  4
2010Q2  2  2
2010Q2  3  4
2010Q2  1  6
2010Q3  2  7
2010Q3  3  8
2010Q4  4  9

Notice that each index value is duplicated. What I want is to return another DataFrame that average over the duplicated index rows and returns another DataFrame that has no duplicates.
e.g.
          a    b
2010Q1  0.5  4.0
2010Q2  2.0  4.0
2010Q3  2.5  7.5
2010Q4  4.0  9.0

I have an idea about how to grab the first or last duplicated row, but I dont know how to average over the duplicates.
e.g.
df[df.index.duplicated(keep = 'first')]
df[df.index.duplicated(keep = 'last')]

A: I think @user3483203's groupby approach is the most straightforward.  But one additional option is to use pivot_table():
df.reset_index().pivot_table(columns=["index"]) # add .T to transpose dates to rows

index  2010Q1  2010Q2  2010Q3  2010Q4
a         0.5     2.0     2.5     4.0
b         4.0     4.0     7.5     9.0


text:
Q: Error compiling rpy2 on python3.4 due to -Werror=declaration-after-statement I ran into an error compiling rpy2 when trying to pip install it:
./rpy/rinterface/_rinterface.c:2376:3: error: ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]

(and many more like it)
This is the call that Python made to the compiler:
gcc -pthread -Werror=declaration-after-statement -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DR_INTERFACE_PTRS=1 -DHAVE_POSIX_SIGJMP=1 -DRIF_HAS_RSIGHAND=1 -DCSTACK_DEFNS=1 -DHAS_READLINE=1 -I./rpy/rinterface -I/home/hen/miniconda3/envs/fitts/include/python3.4m -I/usr/share/R/include -c ./rpy/rinterface/_rinterface.c -o build/temp.linux-x86_64-3.4/./rpy/rinterface/_rinterface.o

A: With some googling, I determined that the problem was the -Werror=declaration-after-statement flag. Trying to figure out where this flag came from. I eventually came across this Python issue:

I got an error while rebuilding a module for 3.4. This was a ISO C90 error but setup.py explicitely adds -std=c99 to the gcc parameters, and indeed it is used.
fifo.h:114:5: error: ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]
  uint32_t ofs = fifo->write_count - fifo->write_offset;
However, Py 3.4 seems to add -Werror=declaration-after-statement also for extension modules. This should not happen (said also Yhg1s in #python).

Until the fix makes its way to you, this can be solved by running
export CFLAGS="-Wno-error=declaration-after-statement"

before running pip install or python setup.py install.


text:
Q: How to organizate custom SQl queres collection I'm developing an app for Windows Phone with SQlite and have a lot of custom  SQL queries. Like
string query = "SELECT distinct(destinations.name) as Destinations
                FROM destinations, flights
                WHERE destinations.d_ID = flights.d_ID
                AND flights.Date = #" + date.ToShortDateString() + "#";

then run:
 var result = (Application.Current as App).db.Query(query);

For working with SQlite i'm using http://dotnetslackers.com/articles/silverlight/Windows-Phone-7-Native-Database-Programming-via-Sqlite-Client-for-Windows-Phone.aspx#s2-introduction-to-sqlite-client-for-windows-phone
and theirs DBHelper
I want all Queries will be in one place, so I can quickly change them.
Wanted to ask how to do it correctly?

*

*create one static class

*create Enum or Dictionary with queries collection

*create some XML or similar file with collection -

Thanks for advise

A: I don't think any of the approaches are valid, for the following reasons:
Create one static class
This is a God object and is considered an anti-pattern, best to stay away from it.  It's just going to be a nightmare to maintain.
create Enum or Dictionary with queries collection
Instead of having a God object now, you have a God collection, and are really just implementing the same anti-pattern in a different way.
Additionally, you'll have string keys (or enum keys) and there's not a strong link between the two (what if the dictionary doesn't populate for some reason?).
create some XML or similar file with collection
It could be argued that you're doing the same thing you would be doing with a dictionary; you'd have to key the query somehow and then look it up.  It's a very brittle approach.
Possible solution
I recommend that you first abstract out your data layer into logical units.  Create a class for data operations which are related.
For example, if you have a few queries and operations that are related to destinations, create an interface that exposes those operations:
public interface IDestinationDataOperations
{
    // Get destinations by date.
    IEnumerable<string> GetDestinationsByDate(DateTime asOf);
}

Then, create a class that implements this which is specific to SQL Lite.  Where you want to make the calls, the variable is of the interface type.
The benefits of this are:

*

*If you change the implementation from SQL Lite to some other underlying data store (web service call, JSON REST call, whatever) you only have to change where you populate the interface variable (this is where dependency injection begins to be of use), as all of your calls are against the abstraction

*The interface is more easily testable:

*

*You can test the direct implementation against any test data you want

*For items that rely on the interface, you can mock the interface any way you like and not have an actual database underneath for testing.

Then, for other data operations, you can wash, rinse, and repeat.
For bonus points, you can separate out the interface into a unit-of-work for writes and a repository for reads, depending on whether what best suits your needs.


text:
Q: Is there any mathematical relation between a harmonic mean and the harmonic mean of shifted values? Let $H$ be the harmonic mean of a set of reals $x_i$.
Can we say anything about the harmonic mean $H'$ of the same set of values, but for which each value is increased by a constant $c\,$?
That is,
$$y_i = x_i + c,\quad \text{for all }i.$$
Is there any mathematical relation between $H$ and $H'\,$?


text:
Q: In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional? I ran into what I think is a strange error in may app.  At the bottom of this question is complete code the reproduces what I am seeing in my app, but here is a quick demonstration.

I create two instances of the same class,  one is declared as an optional conforming to a protocol the other as an optional of a concrete class
For both I can set the computed property via option chaining ie:
anOptionalInstance?.someComputedProperty = ....

for the concrete version I can set the property by unwrapping the optional
if let anInstance = anOptionalInstance {
  anInstance.someComputedProperty = ....
}

For the polymorphic version, I get an error message that says I can't set  the property on the instance.

Below is a complete file that reproduces the issue I am seeing.
Can anyone explain what is happening here?
struct MyStruct {
  var someMember: String
}

protocol MyProtocol {
  var myVar: MyStruct { get set }
}

class MyType: MyProtocol {
  var myVar: MyStruct {
    get {
      return MyStruct(someMember: "some string")
    }
    set {
      println(newValue)
    }
  }
}

class UsingClass {
  var anInstanceOfMyType: MyProtocol?
  var anOtherInstanceOfMyType: MyType?

  func someMethod() {

    anInstanceOfMyType = MyType()
    anInstanceOfMyType?.myVar = MyStruct(someMember: "blah")
    if let anInstanceOfMyType = anInstanceOfMyType {
       // The following line produces this error :Cannot assign to 'myVar' in 'anInstanceOfMyType'
      anInstanceOfMyType.myVar = MyStruct(someMember: "blah blah")
    }

    anOtherInstanceOfMyType = MyType()
    anOtherInstanceOfMyType?.myVar = MyStruct(someMember: "blah")
    if let anOtherInstanceOfMyType = anOtherInstanceOfMyType {
      anOtherInstanceOfMyType.myVar = MyStruct(someMember: "blah blah")
    }
  }
}

A: The problem does happen because you are trying to change the property of the constant anInstanceOfMyType which type is MyProtocol.
1. Why anInstanceOfMyType is a constant?
At the first line of UsingClass, anInstanceOfMyType is actually declared as var. However with the Conditional Unwrapping a constant with name anInstanceOfMyType is created, and you are trying to change a property of that constant
2. Ok but anInstanceOfMyType references an instance of a class, so I should be able to change its properties even if it's a constant
Since anInstanceOfMyType has MyProtocol as type, it could contain a struct or a reference an instance of a class.
So the compiler does apply the safer approach and avoid you to change its properties.
Solution
Limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol's inheritance list. The class keyword must always appear first in a protocol's inheritance list, before any inherited protocols:
protocol MyProtocol: class {
  var myVar: MyStruct { get set }
}

or
If MyProtocol is updated to extend AnyObject
protocol MyProtocol : AnyObject {
    var myVar: MyStruct { get set }
}

then becomes clear that anInstanceOfMyType must refer an instance of a class, in this case your code does compile.


text:
Q: Механизм (способ воплощения) игрового поля в браузере Хочу перевести настольную игру в электронный вид. Должна получиться браузерная игра на несколько человек. Поле игры расчерчено на квадраты, по которым ходят игроки.
Как лучше реализовать игровое поле?

Рассматривал несколько вариантов. Первый(достаточно традиционный) - прибегнуть к флешу. Но, по некоторым причинам, отказался от этого варианта. Второй(в лоб) - сделать таблицу в HTML, и плясать от этого. Этот вариант нравится тем, что все достаточно просто реализуемо.

Есть ли еще какие-нибудь способы? Советы по HTML5?


text:
Q: Xubuntu 15.04 not using all Numix icons My problem involves a few application icons that won't use the numix-circle-icons package for their app icons when active. When browsing the application manager, I can view the numix icons fine, but once opened, they switch to their hideous default icons. Like so...

If you look closely, you'll see that Chrome and Spotify both use their stock icons, not Numix circle. Any way to fix this?