Q: Run other code while awaiting This is probably a stupid question, but my current project is stuck until I figure it out.
Say I have this function.
async function AtoB() {
   try{
      await ACheck();
      let quantity = (ABalance - (1 / ABuy));
      quantity = parseFloat(quantity.toFixed(4));
      exchange.createMarketBuyOrder('A/B', quantity)
      trade();
   } catch(err) {
      console.log(err);
   }
}

The function is awaiting another function called ACheck() that looks like this:
async function ACheck() {
   while(ABalance/ABuy < 10) {
   }
   return true;
}

My issue is that ABalance and ABuy are set in another function that gets their values using CCXT. When AtoB() runs, it stops a setTimeout I have in place that calls the price function every 5 seconds. This effectively means that the function will never run since the values for ABalance and Abuy never update.
Is there any way to run the prices function at the same 5 seconds intervals while awaiting ACheck()?
Thanks in advance

A: You are not allowed to block the main thread if you want to run other things async.
Just have your setTimeout run like it does now, when it fires, calculate ABalance/ABuy. If Abalance/Abuy < 10, do nothing and wait for next setTimeout to fire. If not, do the rest.


Q: Magento get salesrule id from product_id (or entity_id) We are using Magento Enterprise 1.10 and I need a way to get the salesrule_id for each product on category pages as well as product detailed pages. This is pretty easy when you're using the cart.
Basically all I want to do is something like this --> Pseudo query
SELECT rule_id FROM salesrule WHERE entity_id = <entity_id)

Do you know of any way to do this outside of the cart. Is there a method I can call with a product id that return's a rule_id if it exists for this product?
Any suggestion would greatly help me.

A: A product does not have sales rules attached to it and there is no inbuilt method to load rules for a given product. On the cart page it is easy because the rule gets applied to the quote and on each item you can get applied_rule_ids which gives you the ids of any matched rules currently applied to the quote item which is not the same as a product object. So for example, you could have multiple sales rules which apply to the same item so applied_sales_rule_ids would give you all the applied rules not just one.
You could try and load a collection of sales rules and add a filter on the product_ids column and then pass in the entity id of the product. This post here explores this with some code examples and may be of some help.

A: Try to use Mage_CatalogRule_Model_Resource_Rule::getRulesFromProduct().


Q: Query a specific time-range and alert at specific time of the day I need to run a rule at 2 am, querying logs from 0 to 2 am, and alert if matches are found.
So far all the rules I created are frequency rules, but I don't know how to achieve the specific time range for the query, and a specific time for the alert, can someone please help?
(I guess the ANY type could let me add my time range as part of the filter....but then how can I run the rule at 2 am every day?)

A: In UTC:
filter:
  range:
    "@timestamp":
      gte: "now/d+0h"
      lt: "now/d+2h"

A: The now is take the time of the server.
filter:
 - range:
   "@timestamp":
      "from": "now-2h"
       "to": "now"

A: if you want your alert to be effective for specific hours only, you can
create an enhancement that drop the alert if the current time doesnt match your needs
check
https://elastalert.readthedocs.io/en/latest/recipes/adding_enhancements.html
regards


Q: How can I handle multipart/form-data POST requests in my java servlet? I'm having a very hard time dealing with multipart/form-data requests with my java application server.  From what I have found out, the servlet 3.0 specification provides methods such as HttpServletRequest.getParts(), which would be ideal for processing the form data uploaded to my servlet.
However, this method is part of the 3.0 servlet specification, and my application server (Tomcat 6) does not support this yet.  Even with a valid 3.0 web.xml file and the java EE 6 libs, I get the following exception when trying to call getParts():
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getParts()Ljava/util/Collection;

Switching application servers is not really a feasible option for this project.  Are there any third-party libraries available for processing multipart/form-data within java servlets?

A: Tomcat 6 does not and will not support Servlet Specification 3.0. You should attempt doing this on Tomcat 7, but I'm not really sure whether this functionality is present in the beta release that is currently available. The functionality is expected to be present in the production release though.
You could continue using Apache Commons FileUpload like posted in the other answer, or you could use Glassfish (depending on the current phase and type of your project).

A: Check out Apache Commons Fileupload.  It gives you a programmatic API to parse a multipart request, and iterate through the parts of it individually.
I've used it in the past for straightforward multipart processing and it does the job fine without being overly complicated.

A: when we used post method than data are encrypted so we have to used servletfileupload to get requested data and using FileItemIterator  we can get all form data.
i already answer on this link How to process a form sent Google Web Toolkit in a servlet


Q: Why is the insantiation of this singleton class giving different values Why do these two statement give different outcomes...

*

*print(Database().id == Database().id) (which gives False)

*but it gives True this way

d1 = Database()
d2 = Database()
print(d1.id == d2.id)

here's the entire code:
import random

class Database:
    initialized = False

    def __init__(self):
        self.id = random.randint(1, 101)

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Database, cls).__new__(cls, *args, **kwargs)
        return cls._instance

print(Database().id == Database().id)
# False

d1 = Database()
d2 = Database()
print(d1.id == d2.id)
# True

A: __new__() always calls __init__() if the returned instance is of the correct class. This means, every Database() call is still going through and setting a new random value to id.
This id is an instance variable that you have defined, it will not really affect the result of id(), which is why if you do
print(Database() is Database())

it will return True even though the id check returned false. The instance is the same, you just changed id value in between, so they evaluate as False.
In the second case, because the instance is the same, both of them get the value generated by __init__() when you assign d2. You can confirm this by adding a print(d1.id) before and after d2 is assigned.
You need to make use of the initialized boolean to correctly skip the code in __init__()
import random

class Database:
    initialized = False

    def __init__(self):
        if not self.initialized:
            self.id = random.randint(1, 101)
            self.initialized = True

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Database, cls).__new__(cls, *args, **kwargs)
        return cls._instance

Take a look at issue with singleton python call two times __init__  if you want to see other implementations of a singleton class or alternative approaches that avoid singleton entirely.


Q: Why do I get this error? 'NoneType' object has no attribute 'shape' in opencv I'm working on real-time clothing detection. so i borrowed the code from GitHub like this:https://github.com/rajkbharali/Real-time-clothes-detection
but (H, W) = frame.shape[:2]:following error in last line.
Where should I fix it?
from time import sleep
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
from glob import glob
import imutils
from imutils.video import WebcamVideoStream
from imutils.video import FPS

from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/My Drive/experiment/Yolo_mark-master/x64/Release/

Labels = []
classesFile1 = "data/obj.names";
with open(classesFile1, 'rt') as f:
    Labels = f.read().rstrip('\n').split('\n')

np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(Labels), 3), dtype="uint8")

weightsPath = "obj_4000.weights"
configPath = "obj.cfg"

net1 = cv.dnn.readNetFromDarknet(configPath, weightsPath)
net1.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net1.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

image = WebcamVideoStream(src=0).start()
fps = FPS().start()
#'/home/raj/Documents/yolov3-Helmet-Detection-master/safety.mp4'

#while fps._numFrames<100:
while True:
#for fn in glob('images/*.jpg'):
    frame = image.read()
    #frame = imutils.resize(frame,width=500)
    (H, W) = frame.shape[:2]

A: The reason behind your error is that the frame is None(Null). Sometimes, the first frame that is captured from the webcam is None mainly because
(1) the webcam is not ready yet ( and it takes some extra second for it to get ready)
or (2) the operating system does not allow your code to access the webcam.
In the first case, before you do anything on the frame you need to check whether the frame is valid or not :
while True:

    frame = image.read()
    if frame is not None:  # add this line

      (H, W) = frame.shape[:2]

In the other case, you need to check the camera setting in your Operating system.
Also, for capturing the webcam frames there is another method based on the VideoCapure class in Opencv that might be easier to debug.


Q: Implementing channels in haskell -- Tackling the awkward squad

In the paper Tackling the awkward squad, Simon Peyton Jones has provided a "possible implementation" of a Channel.
type Channel a = (MVar (Stream a) , -- Read end
                  MVar (Stream a) ) -- Write end (the hole)

type Stream a = MVar (Item a)

data Item a = MkItem a (Stream a)

Now, he implements a function putChan :: Channel a -> a -> IO () like this
putChan (read, write) val
  = do { new_hole <- newEmptyVar ;
         old_hole <- takeMVar write ;
         putMVar write new_hole ;
         putMVar old_hole (MkItem val new_hole) }

The function above takes a MVar out of write, then puts an empty MVar into it.
Then it writes to the old_hole it extracted from write.
The question is, why does it write to old_hole? It has been taken out from write and its scope is limited to the current block only, then what difference does it make?

A:
The question is, why does it write to old_hole? It has been taken out from write and its scope is limited to the current block only, then what difference does it make?

Not quite. old_hole is "in scope" on the read side. You have to look at newChan for the full picture:
newChan = do {
    read <- newEmptyMVar ;
    write <- newEmptyMVar ;
    hole <- newEmptyMVar ;
    putMVar read hole ;
    putMVar write hole ;
    return (read,write) }

So right after calling newChan the "old_hole" from putChan is the same MVar as hole in newChan. And as channel operations progress, that old_hole is always somewhere nested in the MVars of read.
I found the design of linked list-style channels truly difficult to wrap my head around at first. The illustration from that paper does a decent job of showing the structure, but the basic idea is readers "peel off" a layer of MVar to reveal a value, while writers are inserting values "at the bottom" of the pile of MVars, mainting a pointer to the bottom-most one.
By the way this is the design used in Control.Concurrent.Chan


Q: How to use a homescreen widget button to shutdown a service? I have a button whose WidgetProvider kicks off a service with a
PendingIntent. That works just fine. How do I similarly attach an
event handler to the button so that when it is pressed a second time,
it shuts the service down? Is there an appropriate pattern to follow
for something like this?
Thanks.

A: Use a getBroadcast() PendingIntent, where the BroadcastReceiver calls stopService().
Or, use a getService() PendingIntent, where you send a command to your service that has the service call stopSelf().
Or, switch the service to an IntentService, so it shuts down automatically, if that is a better service implementation for your scenario.


Q: override error android studio I'm doing an Android development course using Android Studio but I'm getting a @Override error in one of the examples that I tried to copy/repeat.
Here the code where I get the error
Handler handler = new Handler(){
    @Override //here I get an error, that is not overriding a class
    public void handlerMessage(Message msg) {
        TextView JeroensText = (TextView) findViewById(R.id.JText);
        JeroensText.setText("Lekker bezig!");
    }
};

Anybody how to solve it?

A: There's no handlerMessage(Message message) method on android.os.Handler class, you should override handleMessage(Message message) method (without the 'r')

A: In both cases:
    Handler handler = new Handler(new Handler.Callback () {
        @Override
        public boolean handleMessage(Message msg) {
            TextView JeroensText = (TextView) findViewById(R.id.JText);
            JeroensText.setText("Lekker bezig!");
            return false;
        }
    });

}

and
    Handler handler  = new Handler () {
        @Override
        public void handleMessage(Message msg) {
            TextView JeroensText = (TextView) findViewById(R.id.JText);
            JeroensText.setText("Lekker bezig!");
        }
    };

as you can see there is handleMessage() method, not handlerMessage().
Hope it help

A: Its just a simple miss - remove that extra 'r' from your hanlderMessage method.
Since there is no 'handlerMessage(Message)' method for Handler. Use either
with Callback
Handler handler = new Handler(new Handler.Callback () {
    @Override
    public boolean handleMessage(Message msg) {
        // handle message here
        return true;
    }
});

or
Handler handler  = new Handler () {
    @Override
    public void handleMessage(Message msg) {
        // handle message herer
    }
};


Q: How to show images in dropdownlist options? I need to have a dropdownlist whose options contains text followed by a small image.
Suppose I have a dropdownlist of fruits. I want to show the options as :
Option 1 : small Image of mango then text Mango
Option 2 : small Image of orange then text Orange
.....................
Is it possible to implement in asp.net 2.0?
If yes then please help with sample code.
I don't want to use JQuery.

A: You can do that server side by just placing <asp:Image ImageUrl="some.gif" /> tags in your ASP.NET code. The browser will show them when the page is loaded.

A: You don't need to use JQuery, use CSS background-image property for every <option>.


Q: How can I upload videos into my youtube account without oAuth consent screen using YT data API v3 I want to upload local videos into my youtube account through my web app without oAuth consent screen. I am using node js as server and react js as frontend.

A: You need to understand the difference between private and public data.  Public data is data that is not owned by any user and is available publicly.
Methods like Search List for example access public data available on YouTube.
Private data is data that is owned by a user.  In order to upload to your YouTube account you need permission to upload to that account.
The Videos.insert method as you can see by the documentation requires that the user have consented to your application accessing their YouTube account. They must have consented to your access with one of the following scopes.

So the answer to your question is that you cant. You need to consent to authorization before your application is going to be allowed to upload to YouTube
upload public videos
Please remember that all videos uploaded via the videos.insert endpoint from unverified API projects created after 28 July 2020 will be restricted to private viewing mode. To lift this restriction, each API project must undergo an audit to verify compliance with the Terms of Service. Please see the API Revision History for more details.
Your application will need to go though application verificatin process before any of the videos you upload will be public


Q: How to count the number of columns in Excel table using VBA? Dim housetypes, elements, NumRowsElements, NumColumnsHousetypes

elements = Range("c10:c19")
housetypes = Range("d9:n9")

NumRowsElements = UBound(elements)
NumColumnsHousetypes = UBound(housetypes)

MsgBox ("NumRowsElements is " & NumRowsElements & " NumColumnsHousetypes is " & NumColumnsHousetypes)

I'm not sure why the above code will show me the correct number of row headers (C10 to C19) but not return the correct number of column headers (D9 to N9)?

A: Both elements and housetypes are 2D arrays, not 1D. The first dimension corresponds to the rows, and the second corresponds to columns.
When using Ubound, if dimension (2nd parameter) is omitted, 1 is assumed.
NumRowsElements = UBound(elements, 1)
NumColumnsHousetypes = UBound(housetypes, 2)

will return the results you want.


Q: Mongo Bulk Insert Spring I am working on understanding Mongo's bulk insert method. I want to insert records that have a unique index, and the duplicates simply get skipped over. I understand I will need an unorded bulk insert, but am having issues with the implementation. I already have logic that has been implemented with .saveAll by mapping through and building an object. I am failing to connect the dots on where to explicitly insert into the bulk operation. Can I not pass my object, or do I need map each key to data. In the examples I have read, they use small objects and specify each key.
List<Employee> employees =
      people.getEmployees().stream()
          .filter(criteria)
          .map(
              e -> {
                return PersonObject.builder()
                    .firstName(person.getFirstName())
                    .lastName(person.getLastName())
                    .gender(person.getGender())
                    .salary(employee.getSalary())
                    .weight(person.getWeight())
                    .height(person.getHeight())
                    .school(Schools.SEC)
                    .family(familyOrgins.getFamily())
                    .hairColor(familyOrgins.getHairColor())
                    .eyeColor(familyOrgins.getEyeColor())
                    .city(city)
                    .state(state)
                    .country(country)
                    .build();
              })
          .collect(Collectors.toList());
          result = employeesRepository.saveAll(employees);

I have tried to inserting after the list of objects has been created like below:
      .build();
          })
      .collect(Collectors.toList());
      BulkWriteResult mongoResult = bulkWrite(itemLocations, false);`

I want to insert using a bulk and if last name is the same, then skip over that person insertion.

A: Here is a very small program that performs an Ordered bulkWrite using Spring.  You can change to unordered by changing the enum value on BulkOperations.BulkMode.  This program will insert 3 records, then delete one, then update one.  Because of the filter predicates in the later bulk commands I had to go with an ordered update.  If you are only inserting you could easily get away with a faster unordered bulk command.
Main.java
package com.example.accessingdatamongodb;

import com.mongodb.bulk.BulkWriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@SpringBootApplication
public class Main implements CommandLineRunner {

    @Autowired
    private MongoOperations mongoTemplate;

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

    @Override
    public void run(String... args) throws Exception {

        // CLEAR THE COLLECTION
        mongoTemplate.remove(new Query(), Customer.class);

        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Customer.class);

        for (Integer i = 0; i < 3; i++)
        {
            Customer customer = new Customer();
            customer.firstName = "Barry";
            customer.id = i.toString();
            bulkOps.insert(customer);
        }

        bulkOps.remove(new Query().addCriteria(new Criteria("i").is(1)));
        bulkOps.updateOne(new Query().addCriteria(new Criteria("i").is(2)), new Update().set("name", "Barry"));

        BulkWriteResult results = bulkOps.execute();
    }
}

For completeness here are the other files in the project...
application.properties
spring.data.mongodb.uri=mongodb://localhost:27017/springtestBulkWrite
spring.data.mongodb.database=springtestBulkWrite

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

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>4.5.0</version>
        </dependency>
    </dependencies>

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

</project>

SimpleMongoConfig.java
 import com.mongodb.client.MongoClient;
 import com.mongodb.ConnectionString;
 import com.mongodb.MongoClientSettings;
 import com.mongodb.client.MongoClients;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.mongodb.core.MongoTemplate;

 @Configuration
 public class SimpleMongoConfig {

     @Value("${spring.data.mongodb.database}")
     private String databaseName;

     @Value("${spring.data.mongodb.uri}")
     private String uri;

     @Bean
     public MongoClient mongo() {
         ConnectionString connectionString = new ConnectionString(uri);
         MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
           .applyConnectionString(connectionString)
           .build();

         return MongoClients.create(mongoClientSettings);
     }

     @Bean
     public MongoTemplate mongoTemplate() throws Exception {
         return new MongoTemplate(mongo(), databaseName);
     }
 }

CustomerRepository.java (not really used in this trivial example)
package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);
  public void deleteByLastName(String lastName);
}

Customer.java
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;

public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }
}


Q: Mod Rewrite Clean URL's How can I transform:

*

*http://example.com/about.php

*http://example.com/hello/deep.php

*http://example.com/hello/world/deeper.php
Dynamically, into URLs like:

*

*http://example.com/about/

*http://example.com/hello/deep/

*http://example.com/hello/world/deeper/

A: see http://gist.github.com/22877


Q: When classifying images to folders Error Comes Failed to get device properties, error code: 30 Keras     examples
data_226000_227000.h5_286.png
D:/Icorve Project/Learn Neural Networks/Looking Straight/data_226000_227000.h5_286.png
(531, 413)
(531, 413, 3)
(180, 140, 1)
[INFO] loading network...
2020-01-07 09:24:19.310174: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
2020-01-07 09:26:35.773432: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
[INFO] classifying image...
examples
data_226000_227000.h5_288.png
D:/Icorve Project/Learn Neural Networks/Looking Straight/data_226000_227000.h5_288.png
(531, 413)
(531, 413, 3)
(180, 140, 1)
[INFO] loading network...
2020-01-07 09:30:36.892513: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
2020-01-07 09:32:51.847629: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
[INFO] classifying image...

When classifying images to folders Error Comes  Failed to get device properties, error code: 30 Keras
Some images are classifying correctly. What this error

A: If you are using two GPU's let's say Intel GPU and NVIDIA GPU, then please choose graphic driver to NVIDIA GPU by opening NVIDIA control Panel.
In case if you are using only one driver then please update NVIDIA GPU graphic driver.


Q: Matplotlib: How to plot with only NAN values? How can I plot a timeseries with timestamps on the x-axis and "data" that contains only NAN on the y-axis using matplotlib?
The goal is to get an empty plot with timestamps on the x-axis and an empty y-axis. Why do I want to have an empty plot? Well, I am creating plots in a loop for every day of the year and it can happen that the timeseries has data gaps (no, interpolation of data gaps makes no sence).
    TIMESTAMP
2019-10-21 12:00:00   NaN
2019-10-21 12:01:00   NaN
2019-10-21 12:02:00   NaN
2019-10-21 12:03:00   NaN
2019-10-21 12:04:00   NaN
                       ..
2019-10-22 11:55:00   NaN
2019-10-22 11:56:00   NaN
2019-10-22 11:57:00   NaN
2019-10-22 11:58:00   NaN
2019-10-22 11:59:00   NaN
Freq: T, Name: df_plot.prec, Length: 1440, dtype: float64

DatetimeIndex(['2019-10-21 12:00:00', '2019-10-21 12:01:00',
               '2019-10-21 12:02:00', '2019-10-21 12:03:00',
               '2019-10-21 12:04:00', '2019-10-21 12:05:00',
               '2019-10-21 12:06:00', '2019-10-21 12:07:00',
               '2019-10-21 12:08:00', '2019-10-21 12:09:00',
               ...
               '2019-10-22 11:50:00', '2019-10-22 11:51:00',
               '2019-10-22 11:52:00', '2019-10-22 11:53:00',
               '2019-10-22 11:54:00', '2019-10-22 11:55:00',
               '2019-10-22 11:56:00', '2019-10-22 11:57:00',
               '2019-10-22 11:58:00', '2019-10-22 11:59:00'],
              dtype='datetime64[ns]', name='TIMESTAMP', length=1440, freq='T')

plt.plot(df_plot.index, df_plot.prec)

results in:
ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

timeseries is of type datetime64


Q: How to get reproducible result when running Keras with Tensorflow backend Every time I run LSTM network with Keras in jupyter notebook, I got a different result, and I have googled a lot, and I have tried some different solutions, but none of they are work, here are some solutions I tried:

*

*set numpy random seed
random_seed=2017
from numpy.random import seed
seed(random_seed)

*set tensorflow random seed
from tensorflow import set_random_seed
set_random_seed(random_seed)

*set build-in random seed
import random
random.seed(random_seed)

*set PYTHONHASHSEED
import os
os.environ['PYTHONHASHSEED'] = '0'

*add PYTHONHASHSEED in jupyter notebook kernel.json
{
 "language": "python",
 "display_name": "Python 3",
 "env": {"PYTHONHASHSEED": "0"},
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ]
}
and the version of my env is:
Keras: 2.0.6
Tensorflow: 1.2.1
CPU or GPU: CPU

and this is my code:
model = Sequential()
model.add(LSTM(16, input_shape=(time_steps,nb_features), return_sequences=True))
model.add(LSTM(16, input_shape=(time_steps,nb_features), return_sequences=False))
model.add(Dense(8,activation='relu'))
model.add(Dense(1,activation='linear'))
model.compile(loss='mse',optimizer='adam')

A: The seed is definitely missing from your model definition. A detailed documentation can be found here: https://keras.io/initializers/.
In essence your layers use random variables as their basis for their parameters. Therefore you get different outputs every time.
One example:
model.add(Dense(1, activation='linear',
               kernel_initializer=keras.initializers.RandomNormal(seed=1337),
               bias_initializer=keras.initializers.Constant(value=0.1))

Keras themselves have a section about getting reproduceable results in their FAQ section: (https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development). They have the following code snippet to produce reproducable results:
import numpy as np
import tensorflow as tf
import random as rn

# The below is necessary in Python 3.2.3 onwards to
# have reproducible behavior for certain hash-based operations.
# See these references for further details:
# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED
# https://github.com/fchollet/keras/issues/2280#issuecomment-306959926

import os
os.environ['PYTHONHASHSEED'] = '0'

# The below is necessary for starting Numpy generated random numbers
# in a well-defined initial state.

np.random.seed(42)

# The below is necessary for starting core Python generated random numbers
# in a well-defined state.

rn.seed(12345)

# Force TensorFlow to use single thread.
# Multiple threads are a potential source of
# non-reproducible results.
# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res

session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)

from keras import backend as K

# The below tf.set_random_seed() will make random number generation
# in the TensorFlow backend have a well-defined initial state.
# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed

tf.set_random_seed(1234)

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)

A: Keras + Tensorflow.
Step 1, disable GPU.
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""

Step 2, seed those libraries which are included in your code, say "tensorflow, numpy, random".
import tensorflow as tf
import numpy as np
import random as rn

sd = 1 # Here sd means seed.
np.random.seed(sd)
rn.seed(sd)
os.environ['PYTHONHASHSEED']=str(sd)

from keras import backend as K
config = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1)
tf.set_random_seed(sd)
sess = tf.Session(graph=tf.get_default_graph(), config=config)
K.set_session(sess)

Make sure these two pieces of code are included at the start of your code, then the result will be reproducible.

A: I resolved this issue by adding os.environ['TF_DETERMINISTIC_OPS'] = '1'
Here an example:
import os
os.environ['TF_DETERMINISTIC_OPS'] = '1'
#rest of the code
#TensorFlow version 2.3.1


Q: Tensorflow keras layers.Multiply() TypeError: 'NoneType' object is not subscriptable I'm a beginning on Keras. I'm trying to convert the following R script into Python
1 library ( keras )
2 # we fit j =0 with feature matrix dat .X , claims dat$C1 and volumes dat$C0
3 dat .Y <- as . matrix ( dat$C1 / sqrt ( dat$C0 )) # observed responses
4 dat .W <- as . matrix ( sqrt ( dat$C0 )) # volumes used as offsets
5 q <- 20 # number of hidden neurons
6 # definition of neural network
7 features <- layer_input ( shape = c( ncol ( dat .X )))
8 net <- features % >%
9 layer_dense ( units = q , activation = ’tanh ’) % >%
10 layer_dense ( units = 1, activation = k_exp )
11 volumes <- layer_input ( shape =c (1))
12 offset <- volumes % >%
13 layer_dense ( units = 1, activation = ’ linear ’ , use_bias = FALSE , trainable = FALSE ,weights = list ( array (1 , dim =c (1 ,1))))
14 weights = list ( array (1 , dim =c (1 ,1))))
15 merged <- list ( net , offset ) % >%
16 layer_multiply ()

Below my script python:
input_shape = SelectedMatrix_Tr.shape[1]
net = Sequential ([
    Dense(20, activation="tanh", input_shape=(input_shape,), name="hidden_layer_1"),
    Dense(1, activation=tf.keras.activations.exponential, name="output_layer")
])

offset =  Sequential([
    Dense(
    units=1,
    activation = 'linear',
    input_shape=(None,1),
    #input_dim=1,
    use_bias = True,
    trainable = False,

    kernel_initializer=tf.constant_initializer(1.)

    )
        ])

multiplied = tf.keras.layers.Multiply()([net,offset])

The error arrives at the last line of Multiply. Below the error message:

TypeError                                 Traceback (most recent call
last)  in
----> 1 multiplied = tf.keras.layers.Multiply()([model,offset])
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py
in call(self, *args, **kwargs)    1021       with
ops.name_scope_v2(name_scope):    1022         if not self.built:
-> 1023           self._maybe_build(inputs)    1024     1025         if self._autocast:
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py
in _maybe_build(self, inputs)    2623         # operations.    2624
with tf_utils.maybe_init_scope(self):
-> 2625           self.build(input_shapes)  # pylint:disable=not-callable    2626       # We must set also ensure
that the layer is marked as built, and the build    2627       # shape
is stored since user defined build functions may not be calling
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\utils\tf_utils.py
in wrapper(instance, input_shape)
268     if input_shape is not None:
269       input_shape = convert_shapes(input_shape, to_tuples=True)
--> 270     output_shape = fn(instance, input_shape)
271     # Return shapes from fn as TensorShapes.
272     if output_shape is not None:
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\layers\merge.py
in build(self, input_shape)
86   def build(self, input_shape):
87     # Used purely for shape validation.
---> 88     if not isinstance(input_shape[0], tuple):
89       raise ValueError('A merge layer should be called on a list of inputs.')
90     if len(input_shape) < 2:
TypeError: 'NoneType' object is not subscriptable

Any suggestions ?
Thanks !


Q: Using One Model inside another model in Django I am Developing a E-commerce Application with Django
So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.
So Here is the code for this
This is the model for getting the Categories from the user

class ProjektCat(models.Model):
    id = models.AutoField(primary_key=True)
    Option_Name = models.CharField(max_length=50)
    Option_Number = models.IntegerField()
    Number_Visits = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.Option_Name}'

and here is the code to list those categories as a dropdown in the CharField
class Software_And_Service(models.Model):
    id = models.AutoField(primary_key=True)
    Product_Name = models.CharField(max_length=100, default='')
    projectKats = ProjektCat.objects.all()
    choice = []
    for i in projectKats:
        option = (i.Option_Number, i.Option_Name)
        choice.append(option)
    Cateogary = models.CharField(
        max_length=256, choices=choice)
    Price = models.IntegerField(default=0)
    Description = models.TextField(default='', max_length=5000)
    pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
    image = models.URLField(default='')
    linkToDownload = models.URLField(default='')

    def __str__(self):
        return f'Projekt : {self.Product_Name}'

But it's Showing me an Error that there is no such table in app_name.projektcat
Is there is any solution for this??

A: It's not how you do this. First correctly assign the projectKats field i.e
# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)

You need to do this logic in django forms rather than django models.
So this is how you can do it.
forms.py
from django import forms
from .models import ProjektCat, Software_And_Service

def get_category_choices():
    return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]

class SoftwareAndServiceForm(forms.ModelForm):
    projectKats = forms.ChoiceField(choices=get_category_choices)

    class Meta:
        model = Software_And_Service
        fields = [
                  'projectKats',
                   # whatever fields you want
                 ]


Q: Can a '.exe' file made through python run on another device with python language not installed? See, I made a python program with about 7 libraries being used and I converted it into a '.exe' file. So, I wondered if I could run this same file on another device with python not installed.
Is it possible?
Please let me know. Thanks.

A: Depends on how you did it. Pyinstaller is a common one that allows you to do that.


Q: Compiling the "at" command for my mips toolchain While cross compiling with the following command :-
./configure CC=/data/designs/pweth-s-t1501/trunk/software/embedded/ar9341/linux/build/gcc-4.3.3/build_mips/staging_dir/usr/bin/mips-linux-uclibc-gcc --host=mips-linux
During the course of the compilation I am getting this kind of an error.
checking Trying to compile a trivial ANSI C program... configure: error: Could not compile and run even a trivial ANSI C program - check CC.
My question is that does not the binary know that it is being cross-compiled so it is natural that the compiled binary will not be running on my machine.
Can anybody please tell me a workaround for the same problem?


Q: SqlDataReader returns last row I am developing an online examination system, but I'm having difficulties trying to read questions from the database to be displayed on an aspx on page load. Please help me out... I only get the last row displayed not all the rows !
I know that the values gets over ridden but how to solve !?
SqlDataReader reader `enter code here`= cmd.ExecuteReader();

while (reader.Read())
{
    LabelRadio1.Questions = reader["questionTitle"].ToString();
    LabelRadio1.Answers = reader["Answer1"].ToString();
    LabelRadio1.Answers = reader["Answer2"].ToString();
    LabelRadio1.Answers = reader["Answer3"].ToString();
    LabelRadio1.Answers = reader["Answer4"].ToString();
    LabelRadio1.Answers = reader["Answer5"].ToString();
}


Q: Add padding based on partial sum I have four given variables:

*

*group size

*total of groups

*partial sum

*1-D tensor
and I want to add zeros when the sum within a group reached the partial sum. For example:

groupsize = 4
totalgroups = 3
partialsum = 15
d1tensor = torch.tensor([ 3, 12,  5,  5,  5,  4, 11])

The expected result is:
[ 3, 12, 0, 0,  5,  5,  5, 0, 4, 11, 0, 0]
I have no clue how can I achieve that in pure pytorch. In python it would be something like this:
target = [0]*(groupsize*totalgroups)

cursor = 0
current_count = 0
d1tensor = [ 3, 12,  5,  5,  5,  4, 11]

for idx, ele in enumerate(target):
  subgroup_start = (idx//groupsize) *groupsize
  subgroup_end = subgroup_start + groupsize
  if sum(target[subgroup_start:subgroup_end]) < partialsum:
     target[idx] = d1tensor[cursor]
     cursor +=1

Can anyone help me with that? I have already googled it but couldn't find anything.

A: Some logic, Numpy and list comprehensions are sufficient here.
I will break it down step by step, you can make it slimmer and prettier afterwards:
import numpy as np

my_val = 15
block_size = 4
total_groups = 3
d1 = [3, 12,  5,  5,  5,  4, 11]
d2 = np.cumsum(d1)
d3 = d2 % my_val == 0 #find where sum of elements is 15 or multiple
split_points= [i+1 for i, x in enumerate(d3) if x] # find index where cumsum == my_val
#### Option 1
split_array = np.split(d1, split_points, axis=0)
padded_arrays = [np.pad(array, (0, block_size - len(array)), mode='constant') for array in split_array] #pad arrays
padded_d1 = np.concatenate(padded_arrays[:total_groups]) #put them together, discard extra group if present
#### Option 2
split_points = [el for el in split_points if el <len(d1)] #make sure we are not splitting on the last element of d1
split_array = np.split(d1, split_points, axis=0)
padded_arrays = [np.pad(array, (0, block_size - len(array)), mode='constant') for array in split_array] #pad arrays
padded_d1 = np.concatenate(padded_arrays)


Q: Core plot. Lables overlapped Hi I have a core plot graphic. By default it looks fine, but if I resize it, lables on x axis are overlapped.
I have dates on x axis, how can I change days to weeks? please see screenshot.
Is it some event which heppen on resize?

A: The default axis labeling policy puts the ticks a constant distance apart. You might try the CPTAxisLabelingPolicyAutomatic labeling policy. This policy will automatically adjust the tick spacing as the plot range changes.


Q: Should bower_components be included into the project? I'm working on an ASP.NET MVC 5 project that was initially using Nuget for static content like Bootstrap, jQuery etc. I have now switched to bower as it is the way to go and is also integrated with visual studio.
I noticed that when installing bower packages, they are not automatically included into the project. So I have left them out for now but is this a good idea? Should bower packages be included or not? It doesn't make any difference to access because in my BundleConfig.cs file I'm still able to link these files to aliases as before.

A: bower will download the entire package using Git.

Your package must be publically available at a Git endpoint (e.g., GitHub). Remember to push your Git tags!

This means that bower will actually download the entire repository/release for you to use in your ASP project. I've tested this with bootstrap and jQuery. These repositories can contain many many files so including them into the .csproj file will clutter your project file and may not be ideal.
This can be compared to using nuget packages where we are only referencing external packages in the packages.config file but we do not include the dll and other assemblies into the project. This leads me to think that bower_components should indeed not be included in the project; this makes no difference to usage as you can still reference the packages and use the files.


Q: How can I shift column values forward if the previous value is in a list of excluded values? I have some TSQL code that produces a de-normalized flat file from nicely organized relational tables. The code completes quickly, and the data isn't overwhelming, so chances are any suggestions would help. I don't have to worry much about performance because this process is only intended to be run 1 time a month. I have some wiggle room in that respect.
The source data, for example's sake, is laid out like this: One person (table 1) can have many incidents (table 2). Each incident can have many codes tied to it (table 3). Each code has an ordered sequence. So after flattening this out, one row in the extract file may look like this:
Name                IncidentId  Code1   Code2   Code3   Code4
Sue Ellen Crandell  1991        abc1    def1    xyz0    888

These de-normalized ordered code columns could potentially go out to over 50. The problem is, that there is a new requirement that if one of the ordered code columns has a value that's in the list of exclusions, then the following ordered code column values should be shifted forward one position. This means that if def1 was in the exclusion list, the row should look like this:
Name                IncidentId  Code1   Code2   Code3   Code4
Sue Ellen Crandell  1991        abc1    xyz0    888     <empty string>

Before I fetch additional relational data and export the results to the file, I use dynamic T-SQL to de-normalize these ordered code values into a temp table. Due to not wanting to mess with the dynamic T-SQL, and probable limitations with being able to use conditionals to shift the columns during that part of the process, I'm thinking that the easiest place to put the exclusion list evaluation would be after the ordered code values make it into the temp table.
If I have a temp table that looks like the first data row above, how can I

*

*Check each column value.

*Remove the value if it is included in the exclusion list

*Conditionally shift values forward when encountering a value in an exclusion list, as shown in the row examples above?

The exclusion list is just a handful of static values that I can either dump into a temp table or use with an IN operator. I'm guessing that a CTE might be needed, but the recursion logic isn't clear to me.

A: First create a CTE that unpivots the table so that each code is on a separate row:
with cte(Name, IncidentId, CodeName, Code)
as(
    select Name, IncidentId, CodeName, Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4)) unpvt
)

Now you do an outer join on the CTE to itself, filtering out the excluded codes.  This gives you one row for each Name-Incident-Code tuple, but you have null values in the rows where the code was excluded (you need the null rows to maintain the proper count of codes).
Select *, t1.Name, t1.IncidentId, isnull(t2.Code, '') Code,
ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeName, 'zzz')) CodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and
           t1.IncidentId = t2.IncidentId and
           t1.Code = t2.Code and
           not exists(select 1 from Exclude e where e.Code = t2.Code)

The ROW_NUMBER() here will create the new CodeNumber.  The order byisnull(t2.CodeNumber, 'zzz')) pushes the null rows to the end so that the rows that have valid codes get numbered first (because "zzz" is greater than "Code-whatever-").
Now you just need to pivot the previous query back so that the codes become columns again:
select Name, IncidentId, [1] Code1, [2] Code2, [3] as Code3, [4] as Code4
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeName, 'zzz')) CodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
pivot(max(Code) for CodeNumber in ([1], [2], [3], [4])
) as pvt

SQL Fiddle
Update
There's a couple problems with the code above.  First, when I create the CodeNumber with ROW_NUMBER(), I am sorting by CodeName.  This breaks down after 9 code columns because they no longer sort correctly (they get sorted alphabetically instead of numerically).  So I need to pull the code number out in the CTE so I can use it to sort by later:
with cte(Name, IncidentId, CodeName, CodeNumber, Code)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 5, len(CodeName))), Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10)) unpvt
)

Now the rest of the query looks like this:
select Name, IncidentId, [1] Code1, [2] Code2, [3] as Code3, [4] as Code4, [5] as Code5, [6] as Code6, [7] as Code7, [8] as Code8, [9] as Code9, [10] as Code10
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber
    from cte t1
    left outer join cte t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
pivot(max(Code) for NewCodeNumber in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])
) as pvt

Note that since I now have a column called CodeNumber in the CTE, I am calling the newly generated number "NewCodeNumber".  Also, I am ordering by t2.CodeNumber instead of t1.Code.
Updated SQL Fiddle.
Update
Regarding the question in your comment, you're essentially asking about unpivoting multiple columns, which is not as straightforward as unpivoting a single column.  One way to accomplish it is to unpivot the code and the codedate separately:
with cteCode(Name, IncidentId, CodeName, CodeNumber, Code)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 5, len(CodeName))), Code
    from Incident i
    unpivot(Code for CodeName in (Code1, Code2, Code3, Code4, Code5, Code6, Code7, Code8, Code9, Code10)) unpvt
), cteCodeDate(Name, IncidentId, CodeName, CodeNumber, CodeDate)
as(
    select Name, IncidentId, CodeName, convert(int, SUBSTRING(CodeName, 9, len(CodeName))), CodeDate
    from Incident i
    unpivot(CodeDate for CodeName in (CodeDate1, CodeDate2, CodeDate3, CodeDate4, CodeDate5, CodeDate6, CodeDate7, CodeDate8, CodeDate9, CodeDate10)) unpvt
)

and then join them back together:
Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber, t3.CodeDate
    from cteCode t1
    join cteCodeDate t3 on t3.Name = t1.Name and t3.IncidentId = t1.IncidentId and t3.CodeNumber = t1.CodeNumber
    left outer join cteCode t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)

Pivoting multiple columns isn't as easy as a single column either, so I went a different route to  get the final result:
select Name, IncidentId,
MAX(case when newCodeNumber = 1 then Code end) Code1,
MAX(case when newCodeNumber = 1 then CodeDate end) CodeDate1,
MAX(case when newCodeNumber = 2 then Code end) Code2,
MAX(case when newCodeNumber = 2 then CodeDate end) CodeDate2,
MAX(case when newCodeNumber = 3 then Code end) Code3,
MAX(case when newCodeNumber = 3 then CodeDate end) CodeDate3,
MAX(case when newCodeNumber = 4 then Code end) Code4,
MAX(case when newCodeNumber = 4 then CodeDate end) CodeDate4,
MAX(case when newCodeNumber = 5 then Code end) Code5,
MAX(case when newCodeNumber = 5 then CodeDate end) CodeDate5,
MAX(case when newCodeNumber = 6 then Code end) Code6,
MAX(case when newCodeNumber = 6 then CodeDate end) CodeDate6,
MAX(case when newCodeNumber = 7 then Code end) Code7,
MAX(case when newCodeNumber = 7 then CodeDate end) CodeDate7,
MAX(case when newCodeNumber = 8 then Code end) Code8,
MAX(case when newCodeNumber = 8 then CodeDate end) CodeDate8,
MAX(case when newCodeNumber = 9 then Code end) Code9,
MAX(case when newCodeNumber = 9 then CodeDate end) CodeDate9,
MAX(case when newCodeNumber = 10 then Code end) Code10,
MAX(case when newCodeNumber = 10 then CodeDate end) CodeDate10
from
(
    Select t1.Name, t1.IncidentId, isnull(t2.Code, '') Code, ROW_NUMBER() over(partition by t1.Name, t1.IncidentId order by isnull(t2.CodeNumber, 999)) NewCodeNumber, t3.CodeDate
    from cteCode t1
    join cteCodeDate t3 on t3.Name = t1.Name and t3.IncidentId = t1.IncidentId and t3.CodeNumber = t1.CodeNumber
    left outer join cteCode t2 on t1.Name = t2.Name and t1.IncidentId = t2.IncidentId and t1.Code = t2.Code and not exists(select 1 from Exclude e where e.Code = t2.Code)
) x
group by Name, IncidentId

SQL Fiddle

A: This is too long for a comment.
This is best handled with dynamic SQL.  Moving things over from column to column to handle exclusions is cumbersome, at best.  It would end up being some variant on:
if code1 is not excluded then code1
   else if code2 is not excluded then code2
   else if code3 is not excluded then code3
   else code4 is not excluded then code4 as code1
if code1 is not excluded
   if code2 is not excluded then code2
   else if code3 is not excluded then code3
   else if code4 is not excluded then code4
and so on, and so on and so on

Instead, you probably have a place where you can add something like this to the dynamic SQL:
where not exists (select 1 from ExcludedCodes ec where ec.code <> the.code)

And you will eliminate them before the pivot.


Q: Dynamic dictionary feature in NMT V3 I have heard that it should be possible to add a dynamic dictionary, holding a set of terms or word list when you train your model. This should be possible in the Translation Hob today.
How to do this using V3 or NMT in portal.customtranslator.azure.ai using custom translator project?
/Mats

A: At this time the dictionary feature is not available in the NMT custom translator but it is a feature we are working on and will release in a future update.


Q: Wordpress/Woocommerce Sessions Good afternoon, I have built a website for me client using Wordpress/Woocommerce. the site works great but one problem is that the basket/session doesn't clear after the order is finished. It looks to me that WooCommerce doesn't even have the feature as standard. Working with the Woocommece standard files, whats the best way to kill a session after the checkout process is complete?
Is there a way around this?

A: Your cart should be clearing after checkout so something else may be wrong.
You could create a function with empty_cart() in it that is triggered when payment is complete "just in case".
See: http://docs.woothemes.com/wc-apidocs/class-WC_Cart.html
add_filter( 'woocommerce_payment_complete_order_status', 'pg_woocommerce_payment_complete_order_status', 10, 2 );
function pg_woocommerce_payment_complete_order_status ( $order_status, $order_id ) {

    $global $woocommerce;
    $woocommerce->cart->empty_cart();

}

A: You can user this hook :
function custom_empty_cart( $order_id, $data ) {
   // delete current cart item here
}

add_action( 'woocommerce_checkout_order_processed', 'custom_empty_cart', 11, 2 );

Or you can check woocommerce hook list from here.

A: The cart should empty as this feature is standard, empty_cart();
Are you using any cache-plugins? In that case you need to exclude the cart page
http://docs.woothemes.com/document/configuring-caching-plugins/
It could also be a problem with the payment-gateway, make sure you have updated to the latest version.

A: i found a similar question but it clears the cart on the click of a button..
http://wordpress.org/support/topic/add-an-empty-cart-button-to-cart-page seems to have worked for some user..
here is the code , it should go in to the function.php file
add_action('init', 'woocommerce_clear_cart_url');
function woocommerce_clear_cart_url() {
    global $woocommerce;
    if( isset($_REQUEST['clear-cart']) ) {
        $woocommerce->cart->empty_cart();
    }
}

this is the code for the button
<input type="submit" class="button" name="clear-cart" value="<?php _e('Empty Cart', 'woocommerce'); ?>" />

im guessing u dont need  a button, so in the next page when u want the cart to be empty, u can explicitly call this function _e('Empty Cart', 'woocommerce');
for example if it you would like to clear the cart in a post page whose title is Payment Success
if(is_single('Payment Success'))
_e('Empty Cart', 'woocommerce');

or if its slug is payment-success
is_single('payment-success');
_e('Empty Cart', 'woocommerce');

similarly to check if its homepage you can use
is_front_page();

or if its on the wordpress page u can use this
if(is_page( 'Payment Success' ))
    _e('Empty Cart', 'woocommerce');

if(is_page( 'payment-success' ))
    _e('Empty Cart', 'woocommerce');

you can include the above code in the head section of your wordpress site!!
Hope this helps


Q: SQLite3 - One cell has different type than other cells in column I have a SQLite3 db. I use SQLite Browser and Python to work with this db. I have a column description which is a text column on the tabe. I've changed the text in one row using Sqlite3 Browser. From then, I'm getting error in python script.
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 36: ordinal not in range(128)

I've tried to catch this exception and print the row and I realised that instead of text, there is object buffer (this is just one cell) other cells in row are ok:
<read-write buffer ptr 0x047684B0, size 4307 at 0x04768490>

This is the only cell with this object, the cells I didn't modified are unicode's.
How to solve this issue? Is there some way to convert buffer to string in the database?
EDIT: python code
with engine.connect() as connection:
    for row in connection.execute('SELECT * FROM final_table'):
        try:
            if any(x in ' '.join(unicode(y) for y in row[:2]+row[3:4]+row[5:13]+row[14:]) for x in ('mm445','xxs', '998s54a')):
                print row[:2]+row[3:4]+row[5:13]+row[14:]
                for x in row:
                    print type(x)
        except:
            print 'exc'
            print row[:2]+row[3:4]+row[5:13]+row[14:]

A: You can use unicode() to convert a byte string from some encoding to Unicode, but unless you specifiy the encoding, Python assumes it's ASCII.
SQLite does not use ASCII but UTF-8, so you have to tell Python about it:
...join(unicode(y, 'UTF-8') for y in ...)


Q: How to separate text using substring I was wondering how can I separate a column containing the following:
 BURGER, Petrus (CHV 494081)

Into 3 columns:
 FirstName, LastName, ID

A: SELECT
  a[2] AS FirstName,
  a[1] AS LastName,
  a[3] AS ID
FROM (
  SELECT regexp_matches(column_name, '(.+), (.+) \((.+)\)')
  FROM table_name
) t(a)


Q: Firebase data structure: Attending school on date I am currently looking into my first application using Firebase as the backend.
I have 2 models, School and User. Each user can sign up for a date to attend the school, so I also need a Date.
A SQL table would look like this:
schools: id, name
users: id, name, email
schools_users: id, school_id, user_id, date
What would be the proper way of designing this data structure in Firebase?

A: Since you don't specify any requirements, I suggest starting with the most naive mapping at first:
root
    schools
        1: "name of school1"
        2: "name of school2"
    users:
        1: { "name": "Maeh", "email": "2523229@stackoverflow.com" }
        2: { "name": "Frank", "email": "209103@stackoverflow.com" }
    schools_users:
        1_1: "20141031"
        1_2: "20130102"


Q: JQuery stops working I have he following JQuery on my page and there is a form on it. After I select a name from the autocomplete function, it disables the mask and datepicker function.
Is there anything wrong on the code?
$().ready(function () {
    $("#name").autocomplete({
        source: "names.php",
        width: 260,
        matchContains: true,
        select: function (event, ui) {
            $('#name').val(ui.item.nome);
            complete_fields();
        }
    });
    $(".data").mask('99/99/9999', {
        placeholder: " "
    });
    $(".data").datepicker({
        dateFormat: 'dd/mm/yy',
        nextText: 'Next',
        prevText: 'Previous'
    });
});


Q: Cannot install a j-text-utils-0.3.3.jar - no main manifest attribute I'm trying to install j-text-utils to make a table. When I click on the jar file, nothing happens. So I tried make a .bat file and run the file from cmd. However, this shows up:
no main manifest attribute, in j-text-utils-0.3.3.jar
I searched around and the problems were mainly with pom.xml and MANIFEST.MF.
I dragged the file in Eclipse and the thing did have both pom.xml and MANIFEST.MF.
Here is what the pom.xml looks like:
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>dnl.utils</groupId>
    <artifactId>j-text-utils</artifactId>
    <packaging>jar</packaging>
    <version>0.3.3</version>
    <name>Java Text Utilities</name>
    <url>http://code.google.com/p/j-text-utils</url>

    <dependencies>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>14.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>org.jvnet.wagon-svn</groupId>
                <artifactId>wagon-svn</artifactId>
                <version>1.9</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
        <repository>
            <uniqueVersion>false</uniqueVersion>
            <id>googlecode</id>
            <url>svn:https://d-maven.googlecode.com/svn/trunk/repo/</url>
        </repository>
    </distributionManagement>

</project>

Here is what the MANIFEST.MF looks like:
Manifest-Version: 1.0
Built-By: danielo
Build-Jdk: 1.7.0_45
Created-By: Apache Maven 3.1.0
Archiver-Version: Plexus Archiver

How may I fix this problem please? :(
I used the download link from Google Code: https://code.google.com/archive/p/j-text-utils/downloads

A: This .jar file is to be used as a library, not a as an executable application.
To access the functionalities, you should write your own application in Java and import the needed classes contained in the j-text-utils-0.3.3.jar file.
To be able to compile your Java code, the j-text-utils-0.3.3.jar needs to be available on the classpath.
See this question for more info : What is a classpath and how do I set it?


Q: Julia immutable struct with mutable list Here's some broken code:
struct NumberedList
  index::Int64
  values::Vector{Int64}

  NumberedList(i) = new(i, Int64[])
end

function set_values!(list::NumberedList, new_values::Vector{Int64})
  list.values = new_values
end

# ---
mylist = NumberedList(1)
set_values!(mylist, [1, 2, 3])

I don't want to do either of these:

*

*I could declare the NumberedList as a mutable struct (making everything mutable)

*I could replace set_values! with something like this (copy all the values):

function set_values!(list::NumberedList, new_values::Vector{Int64})
  for i in new_values
      push!(list.values, i)
  end
end

But I'd like to make index immutable, but allow values to be assigned to.

Other notes:

*

*Thread from the Discourse: "Mutable field in immutable type," but this doesn't apply to vectors in this setting.

A: It depends on what exactly you want to mutate.

*

*If you really want to reassign the field values::Vector{Int64} itself, then you have to use a mutable struct. There's no way around that, because the actual data of the struct changes when you reassign that field.

*If you use an immutable struct with a values::Vector{Int64} field, it means that you cannot change which array is contained, but the array itself is mutable and can change its elements (which are not stored in the struct). In this case, you really do have to copy values to it from external arrays, like your example code (though I would point out that your code did not reset the array to an empty one). I personally think this would be cleaner:

function set_values!(list::NumberedList, new_values::Vector{Int64})
  empty!(list.values) # reset list.values to Int64[]
  append!(list.values, new_values)
end

*The thread you linked talks about using Base.Ref. Base.Ref is pretty much THE way to make a field of an immutable struct indirectly act like a mutable field. It works like this: the field cannot change which RefValue{Vector{Int64}} instance is contained, but the instance itself is mutable and can change its reference (again, not stored in the struct) to any Int64 array. You have to use indexing values[] to get to the array, though:

struct NumberedList
  index::Int64
  values::Ref{Vector{Int64}}

  NumberedList(i) = new(i, Int64[])
end

function set_values!(list::NumberedList, new_values::Vector{Int64})
  list.values[] = new_values # "reassign" different array to Ref
end

# ---
mylist = NumberedList(1)
set_values!(mylist, [1, 2, 3])


Q: call API in R to evaluate each row in data frame I am using this api called rosette_api_key and it works so great. However, it seems to only work by passing one variable at the time.
As per below, variable "h" is a sentence I want to get sentiment analysis on.
library(rosette)
var.name  <- "rosette_api_key"
var.value <- "api key"
args = list(var.value)
names(args) = var.name
do.call(Sys.setenv, args)

h = "This is a cool site"

x = ros_sentiment(paste0(h, collapse=""))

$document
$document$label
[1] "pos"

$document$confidence
[1] 0.6999912

$entities
list()

When I changed "h" to point to a column in a data.frame then it wont accept it.
equally when I changed "h" to multiple sentences like
    h = c("I love my house", "This is a sad day", "My son is cute")
It scores my "h" as one single document but i want it to return 3 different scores for each sentences.
What do I do wrong? Please advice.
Thanks so much
Ped


Q: Highlight very simple code tag in wordpress? In a self hosted wordpress blog, I'm trying to hightlight this code : [xml], inline.
If I put this :
[code language="ps" light="true"][xml][/code]

It outputs as 1
Which html source is :

    1

How can I tell the syntaxt highlight engine to ignore the [xml] tag and render it as is?
Is it possible to hightlight some words in a sentence? (like the ``code`` construct in SO)
[edit] I also tried :
[code language="ps" light="true"][xml][/code]

But it outputs [xml]

A: Use this plugin to highlight code snippets
https://wordpress.org/plugins/crayon-syntax-highlighter/


Q: Tensorflow back_prop ValueError: setting an array element with a sequence I'm getting this value error:ValueError: setting an array element with a sequence, when doing back_prop in tensorflow. I'm using large IMDB dataset and glove 50d pre-trained vectors. I have tried everything converting multi-dimensional list into np.array, converting individual lists into np.array and also did reshape operation x = x.reshape((batch,time_steps,embedding))
on x but it gave me value error ValueError: total size of new array must be unchanged. I think something is wrong with my input but don't know what? You could run this code on your pc by downloading IMDB dataset and 50d glove vectors. Please Help!
Traceback (most recent call last):
  File "nlp.py", line 109, in <module>
    sess.run(minimize_loss,feed_dict={X : x, Y : y})
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 619, in _run
    np_val = np.array(subfeed_val, dtype=subfeed_dtype)
ValueError: setting an array element with a sequence.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np
import math
import os
from nltk.tokenize import TweetTokenizer
batch = 500
start = 0
end = batch - 1
learning_rate = 0.2
num_classes = 8
path = "/home/indy/Downloads/aclImdb/train/pos"
time_steps = 250
embedding = 50

def get_embedding():
    gfile_path = os.path.join("/home/indy/Downloads/glove.6B", "glove.6B.50d.txt")
    f = open(gfile_path,'r')
    embeddings = {}
    for line in f:
        sp_value = line.split()
        word = sp_value[0]
        embedding = [float(value) for value in sp_value[1:]]
        embeddings[word] = embedding
    return embeddings

ebd = get_embedding()

def get_y(file_name):
    y_value = file_name.split('_')
    y_value = y_value[1].split('.')
    return y_value[0]

def get_x(path,file_name):
    file_path = os.path.join(path,file_name)
    x_value = open(file_path,'r')
    for line in x_value:
        x_value = line.replace("

","")
        x_value = x_value.lower()
    tokeniz = TweetTokenizer()
    x_value = tokeniz.tokenize(x_value)
    padding = 250 - len(x_value)
    if padding > 0:
       p_value = ['pad' for i in range(padding)]
       x_value = np.concatenate((x_value,p_value))
    x_value = [ebd['value'] for value in x_value]

    return x_value

def  batch_f(path):
     directory = os.listdir(path)
     y = [get_y(directory[i]) for i in range(len(directory))]
     x = [get_x(path,directory[i]) for i in range(len(directory))]
     return x,y

X = tf.placeholder(tf.float32, [batch,time_steps,embedding])
Y = tf.placeholder(tf.int32, [batch])

def build_nlp_model(x, _units, lstm_layers,num_classes):

     x = tf.transpose(x, [1, 0, 2])
     x = tf.reshape(x, [-1, embedding])
     x = tf.split(0, time_steps, x)

     lstm = tf.nn.rnn_cell.LSTMCell(num_units = _units, state_is_tuple = True)

     multi_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm] * lstm_layers, state_is_tuple = True)

     outputs , state = tf.nn.rnn(multi_lstm,x, dtype = tf.float32)

     weights = tf.Variable(tf.random_normal([_units,num_classes]))
     biases  = tf.Variable(tf.random_normal([num_classes]))

     logits = tf.matmul(outputs[-1], weights) + biases
     return logits

logits = build_nlp_model(X,400,4,num_classes)
c_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits,Y)
loss = tf.reduce_mean(c_loss)

decayed_learning_rate = tf.train.exponential_decay(learning_rate,0,10000,0.9)
optimizer= tf.train.AdamOptimizer(decayed_learning_rate)
minimize_loss = optimizer.minimize(loss)

correct_predict = tf.nn.in_top_k(logits, Y, 1)
accuracy = tf.reduce_mean(tf.cast(correct_predict, tf.float32))

init = tf.initialize_all_variables()

with tf.Session() as sess:
     sess.run(init)
     for i in range(25):
         x, y = batch_f(path)
         sess.run(minimize_loss,feed_dict={X : x, Y : y})
         accu = sess.run(accuracy,feed_dict = {X: x, Y: y})
         cost = sess.run(loss,feed_dict = {X: x,Y: y})
         start = end
         end = (start + batch)
         print ("Minibatch Loss = " + "{:.6f}".format(cost) + ", Training Accuracy= " + "{:.5f}".format(accu))

EDIT: The other error that I'm getting, when I run the code.
(500, 250, 50)
(500,)
Traceback (most recent call last):
  File "nlp.py", line 115, in <module>
    accu = sess.run(accuracy,feed_dict = {X: x, Y: y})
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 372, in run
    run_metadata_ptr)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 636, in _run
    feed_dict_string, options, run_metadata)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 708, in _do_run
    target_list, options, run_metadata)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 728, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.InvalidArgumentError: targets[0] is out of range
     [[Node: InTopK = InTopK[T=DT_INT32, k=1, _device="/job:localhost/replica:0/task:0/cpu:0"](add, _recv_Placeholder_1_0)]]
Caused by op u'InTopK', defined at:
  File "nlp.py", line 102, in <module>
    correct_predict = tf.nn.in_top_k(logits, Y, 1)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 890, in in_top_k
    targets=targets, k=k, name=name)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 704, in apply_op
    op_def=op_def)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/indy/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
    self._traceback = _extract_stack()


Q: UnauthorizedAccessException in visual studio design view I am having a problem with the design view of visual studio where I will get an error when I try to load a Telerik reference specifically Telerik controls for windows 8 when I load that I get the exception when I remove it the exception goes away.
all this happens on a blank xaml with only a grid in it. The project will run fine and show whatever UI I have in the xaml but it just wont show in the design view.
this is the stack trace
    System.UnauthorizedAccessException
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at Microsoft.VisualStudio.Silverlight.AssemblyMetadataHelper.IMetaDataDispenserEx.OpenScope(String szScope, Int32 dwOpenFlags, Guid& riid)
   at Microsoft.VisualStudio.Silverlight.AssemblyMetadataHelper.OpenScope(IMetaDataDispenserEx dispenser, String path)
   at Microsoft.Expression.Utility.AssemblyHelper.TryGetAttributeValueAsString(String path, String attributeName, String& attributeValue, Boolean& attributeExists)
   at Microsoft.Expression.Utility.AssemblyHelper.IsDesignAssembly(String path, Version extensibilityAssemblyVersion)
   at Microsoft.Expression.DesignSurface.Assemblies.ProjectAssemblyResolver.FindBestMetadataAssembly(IEnumerable`1 possiblePaths)
   at Microsoft.Expression.DesignSurface.Assemblies.ProjectAssemblyResolver.FindMetadataAssembly(String assemblyPath, String designerExtension)
   at Microsoft.Expression.DesignSurface.Assemblies.ProjectAssemblyResolver.EnsureDesignMetadataLoaded(Boolean showErrors)
   at Microsoft.Expression.DesignSurface.Assemblies.ProjectAssemblyResolver.AssemblyCollection_EnumerationChanged(Object sender, EnumerationChangedEventArgs`1 e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at Microsoft.Expression.Utility.Collections.NotifyingCollectionBase`1.EventInvoker(EnumerationChangedEventArgs`1 eventArguments)
   at Microsoft.Expression.Utility.Events.SuspendingEventManager`1.ForwardEvents()
   at Microsoft.Expression.Utility.Events.Suspender.SuspendDisposer.Dispose(Boolean disposing)
   at Microsoft.Expression.Utility.Events.Suspender.SuspendDisposer.Dispose()
   at Microsoft.Expression.DesignSurface.Assemblies.AssemblyCollection.AssemblyService_AssembliesUpdated(Object sender, EventArgs`1 e)
   at Microsoft.Expression.DesignSurface.Assemblies.AssemblyService.OnAssembliesUpdated(IEnumerable`1 assemblyInformation)
   at Microsoft.Expression.DesignSurface.Assemblies.AssemblyService.WindowsRuntimeService_IterationContextChanged(Object sender, WindowsRuntimeContextChangedEventArgs e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at Microsoft.Expression.Utility.WindowsRuntimeService.SetIterationContext(String[] paths)
   at Microsoft.Expression.Utility.WindowsRuntimeService.SynchronizeDesignerContext()
   at Microsoft.Expression.Utility.WindowsRuntimeService.ProcessShadowCopyResults(IEnumerable`1 results)
   at Microsoft.Expression.DesignSurface.Assemblies.AssemblyService.FlushShadowCopyUpdateQueue()
   at Microsoft.Expression.DesignSurface.Assemblies.ProjectAssemblyResolver.Project_ReferencesChanged(Object sender, HostItemChangesEventArgs`1 e)
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalEvent`3.<>c__DisplayClass1b.<Invoke>b__1a()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.Invoke(Boolean waitingInExternalCall)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.InvokeCall(Call call)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.DirectInvoke(Boolean inbound, Action action, Int32 sourceApartmentId, Int32 targetApartmentId, Int32 originId, WaitHandle aborted)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.DirectInvokeInbound(Action action, Int32 targetApartmentId)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId, CancellationToken cancelToken, CallSynchronizationMode syncMode, CallModality callModality, String methodName, String filePath, Int32 lineNumber)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action, CallSynchronizationMode syncMode, CallModality callModality, ApartmentState apartmentState, String memberName, String filePath, Int32 lineNumber)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalEvent`3.Invoke(Object sender, TEvent args)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostProject.<>c__DisplayClass9b.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostProjectCallback.OnReferencesChanged>b__9a()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.Invoke(Boolean waitingInExternalCall)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.InvokeCall(Call call)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessQueue(CallQueue queue)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessInboundQueue(Int32 identity)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.ProcessMessage(Int32 msg, IntPtr wParam, IntPtr lParam, Boolean elevatedQuery, Boolean& handled)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.OnWindowMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at Microsoft.Expression.DesignHost.Isolation.Remoting.MessageOnlyHwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at Microsoft.Expression.DesignHost.Isolation.DesignerProcess.RunApplication()
   at Microsoft.Expression.DesignHost.Isolation.DesignerProcess.DesignProcessViewProvider.AppContainerDesignerProcessRun(String[] activationContextArgs)
   at Microsoft.Expression.DesignHost.Isolation.DesignerProcess.DesignProcessViewProvider.<>c__DisplayClass7.<applicationView_Activated>b__6()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

and my xaml
    <Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:t3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Input="using:Telerik.UI.Xaml.Controls.Input"
    x:Class="t3.MainPage"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="Button" HorizontalAlignment="Left" Margin="517,180,0,0" VerticalAlignment="Top"/>
    </Grid>
</Page>

the error really does not seem to give me any information on what the problem is. Any ideas?


Q: Restore On Premises SSAS Database to Azure I've set up an SSAS server on Azure and configured it to connect to an Azure storage account for backups.
Using the Azure Storage Explorer, I've also uploaded a backed-up SSAS database to this same storage account, and I'm trying to restore this backed up db to my SSAS server in Azure.
I've tried to do this using Powershell with
restore-asdatabase -restorefile "mySSASbackup.abf " -name "DBName" -server "asazure://southcentralus.asazure.windows.net/MySSASServer”

But then I get restore-asdatabase : This feature is not supported in AS Azure.
Trying via SSMS: I can connect to the server successfully, but when I try to restore a DB and click on the browse button I get an invalid UNC path notification.
Can anyone help please?

A: You may restore the .abf files into Azure Analysis Servive instance by uploading the file into associated blob storage of AS instance
https://azure.microsoft.com/en-us/blog/backup-and-restore-your-azure-analysis-services-models/
https://www.neowin.net/news/azure-analysis-services-update-brings-backup-and-restore-new-pricing-options-and-more


Q: How to correctly implement a multi-window application in C#? I have a C# Winforms application which supports multiple windows, similar to a browser.
At the moment, when the user launches a new window, I just find the process name and launch the process again.  This seems like a bit of a hack, and it comes with the extra problem that the new window has to do a lot of redundant application initialization work.
I tried this:
var form = new MainForm();
form.Show()

But this has the hidden caveat that closing the main window (which looks like any other window) results in closing all windows.
How can I make my program behave like a browser, where each window is independent but we don't launch a new process every time?
(Note: I think Chrome is an exception in that it launches a new process for each window!)

A: To open a new window:
Thread thread = new Thread(() => Application.Run(new MainForm()))
{
    IsBackground = false
};

thread.Start();

Obviously, this implies that if you access shared state from multiple threads, you need to properly synchronize that access.

A: You can use MDI containers to support multiple windows. Your MainForm will contain all other forms. Other forms can work independent.
Set your main form, MDI container property to true. When creating new form, set mdi parent to your main form.


Q: How to delete completed kubernetes pod? I have a bunch of pods in kubernetes which are completed (successfully or unsuccessfully) and I'd like to clean up the output of kubectl get pods. Here's what I see when I run kubectl get pods:
NAME                                           READY   STATUS             RESTARTS   AGE
intent-insights-aws-org-73-ingest-391c9384     0/1     ImagePullBackOff   0          8d
intent-postgres-f6dfcddcc-5qwl7                1/1     Running            0          23h
redis-scheduler-dev-master-0                   1/1     Running            0          10h
redis-scheduler-dev-metrics-85b45bbcc7-ch24g   1/1     Running            0          6d
redis-scheduler-dev-slave-74c7cbb557-dmvfg     1/1     Running            0          10h
redis-scheduler-dev-slave-74c7cbb557-jhqwx     1/1     Running            0          5d
scheduler-5f48b845b6-d5p4s                     2/2     Running            0          36m
snapshot-169-5af87b54                          0/1     Completed          0          20m
snapshot-169-8705f77c                          0/1     Completed          0          1h
snapshot-169-be6f4774                          0/1     Completed          0          1h
snapshot-169-ce9a8946                          0/1     Completed          0          1h
snapshot-169-d3099b06                          0/1     ImagePullBackOff   0          24m
snapshot-204-50714c88                          0/1     Completed          0          21m
snapshot-204-7c86df5a                          0/1     Completed          0          1h
snapshot-204-87f35e36                          0/1     ImagePullBackOff   0          26m
snapshot-204-b3a4c292                          0/1     Completed          0          1h
snapshot-204-c3d90db6                          0/1     Completed          0          1h
snapshot-245-3c9a7226                          0/1     ImagePullBackOff   0          28m
snapshot-245-45a907a0                          0/1     Completed          0          21m
snapshot-245-71911b06                          0/1     Completed          0          1h
snapshot-245-a8f5dd5e                          0/1     Completed          0          1h
snapshot-245-b9132236                          0/1     Completed          0          1h
snapshot-76-1e515338                           0/1     Completed          0          22m
snapshot-76-4a7d9a30                           0/1     Completed          0          1h
snapshot-76-9e168c9e                           0/1     Completed          0          1h
snapshot-76-ae510372                           0/1     Completed          0          1h
snapshot-76-f166eb18                           0/1     ImagePullBackOff   0          30m
train-169-65f88cec                             0/1     Error              0          20m
train-169-9c92f72a                             0/1     Error              0          1h
train-169-c935fc84                             0/1     Error              0          1h
train-169-d9593f80                             0/1     Error              0          1h
train-204-70729e42                             0/1     Error              0          20m
train-204-9203be3e                             0/1     Error              0          1h
train-204-d3f2337c                             0/1     Error              0          1h
train-204-e41a3e88                             0/1     Error              0          1h
train-245-7b65d1f2                             0/1     Error              0          19m
train-245-a7510d5a                             0/1     Error              0          1h
train-245-debf763e                             0/1     Error              0          1h
train-245-eec1908e                             0/1     Error              0          1h
train-76-86381784                              0/1     Completed          0          19m
train-76-b1fdc202                              0/1     Error              0          1h
train-76-e972af06                              0/1     Error              0          1h
train-76-f993c8d8                              0/1     Completed          0          1h
webserver-7fc9c69f4d-mnrjj                     2/2     Running            0          36m
worker-6997bf76bd-kvjx4                        2/2     Running            0          25m
worker-6997bf76bd-prxbg                        2/2     Running            0          36m

and I'd like to get rid of the pods like train-204-d3f2337c. How can I do that?

A: As previous answers mentioned you can use the command:
kubectl delete pod --field-selector=status.phase=={{phase}}

To delete pods in a certain "phase", What's still missing is a quick summary of what phases exist, so the valid values for a "pod phase" are:

Pending, Running, Succeeded, Failed, Unknown

And in this specific case to delete "error" pods:
kubectl delete pod --field-selector=status.phase==Failed

A: If this pods created by CronJob, you can use spec.failedJobsHistoryLimit and spec.successfulJobsHistoryLimit
Example:
apiVersion: batch/v1
kind: CronJob
metadata:
  name: my-cron-job
spec:
  schedule: "*/10 * * * *"
  failedJobsHistoryLimit: 1
  successfulJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
         ...

A: Here's a one liner which will delete all pods which aren't in the Running or Pending state (note that if a pod name has Running or Pending in it, it won't get deleted ever with this one liner):
kubectl get pods --no-headers=true |grep -v "Running" | grep -v "Pending" | sed -E 's/([a-z0-9-]+).*/\1/g' | xargs kubectl delete pod
Here's an explanation:

*

*get all pods without any of the headers

*filter out pods which are Running

*filter out pods which are Pending

*pull out the name of the pod using a sed regex

*use xargs to delete each of the pods by name

Note, this doesn't account for all pod states. For example, if a pod is in the state ContainerCreating this one liner will delete that pod too.

A: You can do it on two ways.
$ kubectl delete pod $(kubectl get pods | grep Completed | awk '{print $1}')

or
$ kubectl get pods | grep Completed | awk '{print $1}' | xargs kubectl delete pod

Both solutions will do the job.

A: You can do this a bit easier, now.
You can list all completed pods by:
kubectl get pod --field-selector=status.phase==Succeeded

delete all completed pods by:
kubectl delete pod --field-selector=status.phase==Succeeded

and delete all errored pods by:
kubectl delete pod --field-selector=status.phase==Failed

A: If you would like to delete pods not Running, it could be done with one command
kubectl get pods --field-selector=status.phase!=Running

Updated command to delete pods
kubectl delete pods --field-selector=status.phase!=Running

A: Here you go:
kubectl get pods --all-namespaces |grep -i completed|awk '{print "kubectl delete pod "$2" -n "$1}'|bash

you can replace completed with CrashLoopBackOff or any other state...

A: I think pjincz handled your question well regarding deleting the completed pods manually.
However, I popped in here to introduce a new feature of Kubernetes, which may remove finished pods automatically on your behalf. You should just define a time to live to auto clean up finished Jobs like below:
apiVersion: batch/v1
kind: Job
metadata:
  name: remove-after-ttl
spec:
  ttlSecondsAfterFinished: 86400
  template:
    ...

A: Here is a single command to delete all pods that are terminated, Completed, in Error, etc.
kubectl delete pods --field-selector status.phase=Failed -A --ignore-not-found=true

If you are using preemptive GKE nodes, you often see those pods hanging around.
Here is an automated solution I setup to cleanup: https://stackoverflow.com/a/72872547/4185100


Q: Is there a framewok / API I could use to export iPhone-SDK's ABRecordRef instances to vCard? I'm looking at source code from Funambol, but the dependencies are so huge, I'm rethinking of using them, not to mention the code is based on OC++. Can anyone help me out on this?
Thanks.

A: No, afraid not.
You can either try to find a library / sample code in C/C++/ObjC that will generate a vCard from provided information, or attempt to roll your own.
You can find more information about vCard including the specs here; http://www.imc.org/pdi/


Q: Config file location and binaries and build systems like autoconf Most build systems, like autoconf/automake, allow the user to specify a target directory to install the various files needed to run a program.  Usually this includes binaries, configuration files, auxilliary scripts, etc.
At the same time, many executables often need to read from a configuration file in order to allow a user to modify runtime settings.
Ultimately, a program (let's say, a compiled C or C++ program) needs to know where to look to read in a configuration file.  A lot of times I will just hardcode the path as something like /etc/MYPROGAM/myprog.conf, which of course is not a great idea.
But in the autoconf world, the user might specify an install prefix, meaning that the C/C++ code needs to somehow be aware of this.
One solution would be to specify a C header file with a .in prefix, which simply is used to define the location of the config file, like:
const char* config_file_path = "@CONFIG_FILE_PATH@"; // `CONFIG_FILE_PATH` is defined in `configure.ac`.

This file would be named something like constants.h.in and it would have to be process by the configure.ac file to output an actual header file, which could then be included by whatever .c or .cpp files need it.
Is that the usual way this sort of thing is handled?  It seems a bit cumbersome, so I wonder if there is a better solution.

A: There are basically two choices for how to handle this.
One choice is to do what you've mentioned -- compile the relevant paths into the resulting executable or library.  Here it's worth noting that if files are installed in different sub-parts of the prefix, then each such thing needs its own compile-time path.  That's because the user might specify --prefix separately from --bindir, separately from --libexecdir, etc.  Another wrinkle here is that if there are multiple installed programs that refer to each other, then this process probably should take into account the program name transform (see docs on --program-transform-name and friends).
That's all if you want full generality of course.
The other approach is to have the program be relocatable at runtime.  Many GNU projects (at least gdb and gcc) take this approach.  The idea here is for the program to attempt to locate its data in the filesystem at runtime.  In the projects I'm most familiar with, this is done with the libiberty function make_relative_prefix; but I'm sure there are other ways.
This approach is often touted as being nicer because it allows the program's install tree to be tared up and delivered to users; but in the days of distros it seems to me that it isn't as useful as it once was.  I think the primary drawback of this approach is that it makes it very hard, if not impossible, to support both relocation and the full suite of configure install-time options.
Which one you pick depends, I think, on what your users want.
Also, to answer the above comment: I think changing the prefix between configure- and build time is not really supported, though it may work with some packages.  Instead the usual way to handle this is either to require the choice at configure time, or to supported the somewhat more limited DESTDIR feature.