text:
Q: Django 1.1 forms, models and hiding fields Consider the following Django models:
class Host(models.Model):
    # This is the hostname only
    name = models.CharField(max_length=255)

class Url(models.Model):
    # The complete url
    url = models.CharField(max_length=255, db_index=True, unique=True)
    # A foreign key identifying the host of this url
    # (e.g. for http://www.example.com/index.html it will
    # point to a record in Host containing 'www.example.com'
    host = models.ForeignKey(Host, db_index=True)

I also have this form:
class UrlForm(forms.ModelForm):
    class Meta:
        model = Urls

The problem is the following: I want to compute the value of the host field automatically,
so I don't want it to appear on the HTML form displayed in the web page.
If I use 'exclude' to omit this field from the form, how can I then use the form to save information
in the database (which requires the host field to be present) ?

A: Use commit=False:
result = form.save(commit=False)
result.host = calculate_the_host_from(result)
result.save()

A: You can use exclude and then in the forms "clean" method set whatever you want.
So in your form:
class myform(models.ModelForm):
   class Meta:
       model=Urls
       exclude= ("field_name")
   def clean(self):
      self.cleaned_data["field_name"] = "whatever"
      return self.cleaned_data


text:
Q: org.apache.hadoop.mapred.LocalClientProtocolProvider not found I wrote a program to execute a embeded Pig sentence in Java. I executed the java sentence registryQuery. But when I try on to store the result, I give a error of org.apache.hadoop.mapred.localClientProtocolProvider not found. I don't understand this error.
Attached are the sentences:
This is the java code
 pigServer.registerQuery("source = load '"+ inputFile + "' USING    org.apache.pig.backend.hadoop.hbase.HBaseStorage( " +
"'datos:bikes', '-loadKey true')"+
"as (id1:int, bikes:int) ;");

Path output = new Path("consulta1");

 pigServer.store("source","consulta1");

This is the java Exception:
14/06/07 04:01:27 INFO pigstats.ScriptState: Pig features used in the script: UNKNOWN
14/06/07 04:01:27 WARN conf.Configuration: mapred.textoutputformat.separator is deprecated. Instead, use mapreduce.output.textoutputformat.separator
14/06/07 04:01:27 INFO mapReduceLayer.MRCompiler: File concatenation threshold: 100 optimistic? false
14/06/07 04:01:27 INFO mapReduceLayer.MultiQueryOptimizer: MR plan size before optimization: 1
14/06/07 04:01:27 INFO mapReduceLayer.MultiQueryOptimizer: MR plan size after optimization: 1
Exception in thread "main" java.util.ServiceConfigurationError:
    org.apache.hadoop.mapreduce.protocol.ClientProtocolProvider: Provider
    org.apache.hadoop.mapred.LocalClientProtocolProvider not found
at java.util.ServiceLoader.fail(ServiceLoader.java:214)
at java.util.ServiceLoader.access$400(ServiceLoader.java:164)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:350)
at java.util.ServiceLoader$1.next(ServiceLoader.java:421)
at org.apache.hadoop.mapreduce.Cluster.initialize(Cluster.java:90)
at org.apache.hadoop.mapreduce.Cluster.<init>(Cluster.java:83)
at org.apache.hadoop.mapreduce.Cluster.<init>(Cluster.java:76)
at org.apache.hadoop.mapred.JobClient.init(JobClient.java:478)
at org.apache.hadoop.mapred.JobClient.<init>(JobClient.java:457)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher.launchPig(MapReduceLauncher.java:152)
at org.apache.pig.PigServer.launchPlan(PigServer.java:1266)
at org.apache.pig.PigServer.executeCompiledLogicalPlan(PigServer.java:1251)
at org.apache.pig.PigServer.storeEx(PigServer.java:933)
at org.apache.pig.PigServer.store(PigServer.java:900)
at org.apache.pig.PigServer.store(PigServer.java:868)
at bicing.pig.PigEstadisticas.runMyQuery(PigEstadisticas.java:97)
at bicing.pig.PigEstadisticas.main(PigEstadisticas.java:45)

What is org.apache.hadoop.mapred.LocalClientProtocolProvider?
Could somebody help me?

A: It's an old question, but since this could help someone else, I am answering it.
Cause of this problem is that the class

org.apache.hadoop.mapred.LocalClientProtocolProvider

is not found in your class-path. I resolved this error in my setup by adding below maven dependency.
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-mapreduce-client-common</artifactId>
    <version>2.4.1</version>
</dependency>

As far as the functionality of this class is concerned, I do not have more information as of now, as I myself am learning hadoop and Pig.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confused between locking shared resources and Threads running in parallel So first I learned that with creating a new thread, we can run the program in parallel...then I learned there are shared resources like Console that we should lock it down so until one thread is not done yet, another thread won't enter. So isn't this in conflict with Parallel threading? Doesn't it go back to a Sync app ?

A: You only need to lock specific resources that aren't thread safe. I highly suggest you take a look at this five part article on multithreaded programming. The second part, Synchronization, talks about locking. Give the whole thing a read, it's very informative.


text:
Q: How to write console.log wrapper for Angular2 in Typescript? Is there a way to write a global selfmade mylogger function that I could use in Angular2 typescript project for my services or components instead of console.log function ?
My desired result would be something like this:
mylogger.ts
function mylogger(msg){
    console.log(msg);
};

user.service.ts
import 'commons/mylogger';
export class UserService{
  loadUserData(){
    mylogger('About to get something');
    return 'something';
  };
};

A: If you want to use 'console.log' function just in your component you can do this:
import { Component, OnInit } from '@angular/core';

var output = console.log;

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor() { }

  ngOnInit() { }

  printFunction(term: string): void {
    output('foo');
  }
}

A: You could write this as a service and then use dependency injection to make the class available to your components.
import {Injectable, provide} from 'angular2/core';

// do whatever you want for logging here, add methods for log levels etc.
@Injectable()
export class MyLogger {

  public log(logMsg:string) {
    console.log(logMsg);
  }
}

export var LOGGING_PROVIDERS:Provider[] = [
      provide(MyLogger, {useClass: MyLogger}),
    ];

You'll want to place this in the top level injector of your application by adding it to the providers array of bootstrap.
import {LOGGING_PROVIDERS} from './mylogger';

bootstrap(App, [LOGGING_PROVIDERS])
  .catch(err => console.error(err));

A super simple example here: http://plnkr.co/edit/7qnBU2HFAGgGxkULuZCz?p=preview

A: The example given by the accepted answer will print logs from the logger class, MyLogger, instead of from the class that is actually logging.
I have modified the provided example to get logs to be printed from the exact line that calls MyLogger.log(), for example:
get debug() {
    return console.debug.bind(console);
}
get log() {
    return console.log.bind(console);
}

I found how to do it here: https://github.com/angular/angular/issues/5458
Plunker: http://plnkr.co/edit/0ldN08?p=preview
As per the docs in developers.mozilla,
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.

More information about bind here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

A: How about using console on your main service, So we can customize and apply console.log conditionally:
myComponent.ts
export class myComponent implements OnInit {
 constructor(
        private config: GlobalService
    ) {}

    ngOnInit() {
       this.config.log('func name',{a:'aval'},'three');
    }
}

global.service.ts
@Injectable()
export class GlobalService {

   constructor() { }
   this.prod = true;
   public log(one: any, two?: any, three?: any, four?: any) {
        if (!this.prod) {
             console.log('%c'+one, 'background:red;color:#fff', two, three, four);
        }
    }
}

(Note: first parameter should be string in this example);

A: For toggling console.log ON\OFF:
logger.service.ts:
import { Injectable } from '@angular/core';

@Injectable()
export class LoggerService {

private oldConsoleLog = null;

enableLogger(){

    if (this.oldConsoleLog == null) { return; }

    window['console']['log'] = this.oldConsoleLog;
}

disableLogger() {
    this.oldConsoleLog = console.log;
    window['console']['log'] = function () { };
};

}

app.component.ts:
@Component({
  selector: 'my-app',
  template: `your templ;ate`
})

export class AppComponent {

constructor(private loggerService: LoggerService) {
    var IS_PRODUCTION = true;

    if ( IS_PRODUCTION ) {
        console.log("LOGGER IS DISABBLED!!!");
        loggerService.disableLogger();
    }

}
}

A: I created a logger based on the provided information here
Its very basic (hacky :-) ) at the moment, but it keeps the line number
@Injectable()
export class LoggerProvider {

constructor() {
  //inject what ever you want here
}

public getLogger(name: string) {
  return {

    get log() {
      //Transform the arguments
      //Color output as an example
      let msg = '%c[' + name + ']';
      for (let i = 0; i < arguments.length; i++) {
        msg += arguments[i]
      }

      return console.log.bind(console, msg, 'color:blue');
    }

  }
 }
}

Hope this helps

A: type safer(ish) version with angular 4, typescript 2.3
logger.service.ts
import { InjectionToken } from '@angular/core';

export type LoggerService = Pick<typeof console,
                                 'debug' | 'error' | 'info' | 'log' | 'trace' | 'warn'>;
export const LOGGER_SERVICE = new InjectionToken('LOGGER_SERVICE');
export const ConsoleLoggerServiceProvider = { provide: LOGGER_SERVICE, useValue: console };

my.module.ts
// ...
@NgModule({
  providers: [
    ConsoleLoggerServiceProvider,
    //...
  ],
// ...

my.service.ts
// ...
@Injectable()
export class MyService {

  constructor(@Inject(LOGGER_SERVICE) log: LoggerService) {
//...

A: There is now an angular2 logger component on NPM which supports log levels.
https://www.npmjs.com/package/angular2-logger


text:
Q: D3.js to manage Webkit translate3d : Is that possible? Does anybody know how to use CSS3 Webkit translate3d instead of normal left css with d3.js. On iPhone translate3d run faster and I need to do it on a transition after a release of an HTML element.
Here is my code for the left css :
d3.select("#myHTMLElem").transition()
    .style("left", myNewPosX) + "px")
    .duration(500)
    .ease("cubic-in-out")
    .each("end", function(d) {
        // Do something after
});

There is something with JQuery, but I would prefer to keep using d3.js for this project.
Any idea how to make the previous code using the translate3d instead of the left property?
Thanks

A: this is how I do it.
For a smooth/functional transition, make sure you apply the default values to the style attribute before the transition is executed on the element.
Default Style (before transition):
var svg = d3.select("div#wrapper").append("svg").append("g").attr("id", "usg").attr("style", function () {
    return "-webkit-transform: perspective(800) scale(1) scale3d(1, 1, 1) rotate3d(1, 0, 0, 0deg) translate3d(0, 0, 0);";
});

Transition Style (transform the default values):
d3.select("#usg").transition().duration(2000).attr("style", function () {
    return "-webkit-transform: perspective(800) scale(1) scale3d(1, 1, 2) rotate3d(1, 0, 0, 55deg) translate3d(0px, 198px, 0px);";
});


text:
Q: Ubuntu 19.10: No sound (speakers or headphones) on Asus Zenbook UX533FTC Some weeks ago I bought a new Asus Zenbook UX533FTC with preinstalled Windows 10. The sound worked fine until I  reinstalled Ubuntu on the PC.

For deciding this problem I:

*

*Uppdated BIOS version to the newest;

*Reinstalled ALSA with this commands:

*

*sudo apt-get remove --purge alsa-base pulseaudio

*sudo apt-get install alsa-base pulseaudio

*sudo alsa force-reload.

*Installed pavucontrol which says that sound works fine;

*Updated kernel from 5.3.0 to 5.5.5

But... Nothing helped.
Also the sound doesn't work in LiveUSB with Ubuntu 19.10/18.04 and with installed 18.04.
How may I proceed with solving this problem?

A: I had the same problem with my Asus Zenbook UX430UA, all you have to do, every time sound doesnt work put your laptop on Sleep Mode and the sound will work!
For headphones, try this: edit /etc/modprobe.d/alsa-base.conf (I think on some computers, it may be just alsa.conf) and insert this as the last line:
options snd-hda-intel model=headset-mode


text:
Q: How to fix this ValueError? I am trying to run a python code, mostly based on NLTK book, for ngram POS Tagging a Gujarati language text from my GujaratiTextCorpus. I encountered a ValueError.
I am working with Python 3.7.3 in Windows 10. I use jupyter notebook through anaconda. I am a beginner in using python. I studied the answers available on stackoverflow. com to fix my ValueError, but could not solve it.
import nltk
f = open('C:\\Users\\BHOGAYATA\\Documents\\GujaratiPosTagging\\cts260.txt', encoding = 'utf8')
raw = f.read()
train2_sents = nltk.sent_tokenize(raw)
text2 = nltk.Text(train2_sents)
train2_sents
import nltk
f = open('C:\\Users\\BHOGAYATA\\Documents\\GujaratiPosTagging\\txt42_sents.txt', encoding = 'utf8')
raw = f.read()
bs_sents = nltk.sent_tokenize(raw)
text3 = nltk.Text(bs_sents)
bs_sents
unigram_tagger = nltk.UnigramTagger(train2_sents)
unigram_tagger.tag(bs_sents)

I expected that the words of the two Gujarati sentences would be POS Tagged. I found the following error messages:
ValueError
Traceback (most recent call last)
<ipython-input-3-5fae0b92393e> in <module>
     11 text3 = nltk.Text(bs_sents)
     12 bs_sents
---> 13 unigram_tagger = nltk.UnigramTagger(train2_sents)
     14 unigram_tagger.tag(bs_sents)
     15

~\Anaconda3\lib\site-packages\nltk\tag\sequential.py in __init__(self, train, model, backoff, cutoff, verbose)
    344
    345     def __init__(self, train=None, model=None, backoff=None, cutoff=0, verbose=False):
--> 346         NgramTagger.__init__(self, 1, train, model, backoff, cutoff, verbose)
    347
    348     def encode_json_obj(self):

~\Anaconda3\lib\site-packages\nltk\tag\sequential.py in __init__(self, n, train, model, backoff, cutoff, verbose)
    293
    294         if train:
--> 295             self._train(train, cutoff, verbose)
    296
    297     def encode_json_obj(self):

~\Anaconda3\lib\site-packages\nltk\tag\sequential.py in _train(self, tagged_corpus, cutoff, verbose)
    181         fd = ConditionalFreqDist()
    182         for sentence in tagged_corpus:
--> 183             tokens, tags = zip(*sentence)
    184             for index, (token, tag) in enumerate(sentence):
    185                 # Record the event.

ValueError: not enough values to unpack (expected 2, got 1)

A: It says the variable you are passing have one output but you are expecting two..
Ex:
for a, b in [("a", "b")]:
    print("a:", a, "b:", b)

This will work

for a, b in [("a")]:
    print("a:", a, "b:", b)

This will not work

Edit:
Look at your UnigramTagger
For first argument it takes a list of tagged sentences of type
  list(list(tuple(str, str)))

You are giving train2_sents of type
  list(tuple(str,str)

Where your
list(tuple(str,str) is same as train2_sents


text:
Q: 'GC overhead limit exceeded' error when running gradle mlExportBatchesToDirectory I am receiving a 'GC overhead limit exceeded' error when running gradle mlExportBatchesToDirectory.
The gradle command is:
gradle mlExportBatchesToDirectory -PexportPath=/qa2/tgtfiles/Customer -PbatchSize=25000 -Ptransform=CustomerTransform,querydate1,"$querydate1" -PfilenamePrefix="Customer_Daily_$(date "+%Y%m%d")_" -PfilenameExtension=.json -PwhereUrisQuery='cts.andQuery([cts.collectionQuery("latest"),cts.orQuery([cts.andQuery([cts.collectionQuery("customer"),cts.jsonPropertyScopeQuery("PolicyDownloadInfo", cts.trueQuery())]),cts.collectionQuery("customerpreference"),cts.collectionQuery("registrationcontacts")]),cts.notQuery(cts.jsonPropertyValueQuery("PartyId", "defaultprimary")),cts.notQuery(cts.jsonPropertyValueQuery("PartyId", "defaultadditional"))])' -PenvironmentName=qa

Even if I reduce the batch sizes down to 50, the error still occurs.


text:
Q: Python table scrape I'm trying to scrape the "Major Stock Indexes table" from https://markets.wsj.com/ and would like to save it to a folder on my desktop.  This is what I have so far:
import urllib.request
import json
import re

html = urllib.request.urlopen("https://markets.wsj.com/").read().decode('utf8')
json_data = re.findall(r'pws_bootstrap:(.*?)\s+,\s+country\:', html, re.S)
data = json.loads(json_data[0])

filename = "C:\Users\me\folder\sample.csv"
f = open(filename, "w")

for numbers in data['chart']:
    for obs in numbers['Major Stock Indexes']:
        f.write(str(obs['firstCol']) + "," + str(obs['dataCol']) + "," + str(obs['dataCol priceUp']) + str(obs['dataCol lastb priceUp']) + "\n")

print(obs.keys())

I'm getting the error: IndexError: list index out of range
Any ideas what might fix my issue?

A: your json_data an empty list [], you should use the scraping tool like bs4 as below:
from bs4 import BeautifulSoup
import urllib.request
html = urllib.request.urlopen("https://markets.wsj.com/").read().decode('utf8')
soup = BeautifulSoup(html, 'html.parser')  # parse your html
t = soup.find('table', {'summary': 'Major Stock Indexes'})  # finds tag table with attribute summary equals to 'Major Stock Indexes'
tr = t.find_all('tr')  # get all table rows from selected table
row_lis = [i.find_all('td') if i.find_all('td') else i.find_all('th') for i in tr if i.text.strip()]  # construct list of data
print([','.join(x.text.strip() for x in i) for i in row_lis])

Output:
[',Last,Change,% CHG,',
 'DJIA,26049.64,259.29,1.01%',
 'Nasdaq,8017.90,71.92,0.91%',
 'S&P 500,2896.74,22.05,0.77%',
 'Russell 2000,1728.41,2.73,0.16%',
 'Global Dow,3105.09,3.73,0.12%',
 'Japan: Nikkei 225,22930.58,130.94,0.57%',
 'Stoxx Europe 600,385.57,2.01,0.52%',
 'UK: FTSE 100,7577.49,14.27,0.19%']

Now you can just iterate over this list and store it in csv instead of printing it.


text:
Q: get the last part of url (.htaccess) I want to get the last part of the url as a GET request (with htaccess RewriteRule) like the following :
http://localhost/services/rest/users/availability/detailed/Player

to :
http://localhost/services/rest/users/availability/detailed?name=player

I have tried :
RewriteRule ^detailed/(.*)$ index.php?name=$1


text:
Q: Interpreting mcelog output for bad DIMM I'm getting streams of mcelog errors on a machine to which I don't have physical access. It seems like a bad DIMM, but I'm having a hard time determining exactly which one.
mcelog output looks like
Hardware event. This is not a software error.
MCE 0
CPU 1 BANK 5
MISC 21402a2a86 ADDR a8c35dcc0
TIME 1452026764 Tue Jan  5 12:46:04 2016
MCG status:
MCi status:
Error overflow
Corrected error
MCi_MISC register valid
MCi_ADDR register valid
MCA: MEMORY CONTROLLER RD_CHANNEL3_ERR
Transaction: Memory read error
STATUS cc0000c000010093 MCGSTATUS 0
MCGCAP 1000c14 APICID 20 SOCKETID 1
CPUID Vendor Intel Family 6 Model 45

Hardware event. This is not a software error.
MCE 1
CPU 1 BANK 11
MISC 90840000000208c ADDR a089ddac0
TIME 1452026764 Tue Jan  5 12:46:04 2016
MCG status:
MCi status:
Corrected error
MCi_MISC register valid
MCi_ADDR register valid
MCA: MEMORY CONTROLLER MS_CHANNEL3_ERR
Transaction: Memory scrubbing error
STATUS 8c000050000800c3 MCGSTATUS 0
MCGCAP 1000c14 APICID 20 SOCKETID 1
CPUID Vendor Intel Family 6 Model 45

There's a lot of inconsistency between my output and the mcelog documentation. My first problem is that there are 2 8-core Xeons and normally I would assume that they are numbered 0 and 1. However, some posts I've read suggest that the "first" CPU might be labeled by mcelog as CPU 0-7, and the "second" as CPU 8-15.
The second problem is that I can't figure out what BANK 5 means. It's not synonymous with the DIMM slots, because right now we are only using slots 1-4. dmidecode helpfully reports "Bank Locator: Not Specified" on every DIMM.
Also, MEMORY CONTROLLER MS_CHANNEL3_ERR makes me think that the error is coming in on channel 3. According to the motherboard diagram, channel 3 is for slots 4, 8, and 12, which would mean mean the DIMM in 4 is the culprit, but I'm not sure how to verify that.
I have tried mcelog with the --dmi switch, but it fails and suggests and update. This machine is badly out of date (Ubuntu 12.04, and not even the latest packages for that release), but updating it opens another can of worms. I'd like to get this memory problem fixed before I try anything else drastic.
I'm grateful for any help in interpreting this and figuring out what to replace before I send someone on the long drive to the data center.

A: I never did find a clear interpretation of the mcelog data, but my best guess worked out, and I figured I should follow up for posterity.

*

*I assumed CPU 1 meant the second CPU, helpfully labeled as 2 on the
motherboard diagram.

*I assumed MEMORY CONTROLLER MS_CHANNEL3_ERR indicated channel 3 on that CPU's memory controller. As above, that channel controls slots 4, 8 and 12, and only slot 4 had a chip in it.

*I ignored everything else.

I had someone swap out that DIMM, and, presto! No more streams of Machine Check errors.


text:
Q: Dirichlet's unit theorem in finite characteristic I'm looking for a source of the following analog of Dirichlet's unit theorem for finite characteristic fields:
Let $\mathbb{F}_p$ be a finite field and denote $K=\mathbb{F}_p(x)$ to be the field of rational functions over $\mathbb{F}_p$, i.e. functions of the form $\frac{\sum_{n=0}^{N}a_nx^n}{\sum_{n=0}^Mb_n x^n}$ where $a_n,b_n\in \mathbb{F}_p$. This is the field of fractions of $\mathbb{F}_p[x]$, the ring of polynomials over $\mathbb{F}_p$. Here, we have a norm defined by $\Vert \sum_{k=-\infty}^{N}a_kx^k\Vert=p^N$ if $a_N\neq 0$. Let $L$ be a field extension of $K$ of finite rank and let $\sigma_1,\dots \sigma_n:L\rightarrow \bar{K}$ be the embeddings. Denote by $\mathcal{O}_L$ the algebraic integers in $L$, i.e. the elements $t\in L$ which are roots of polynomials with coefficients in $K$. We can look at the $\mathcal{O}_L^*$, the group of units in $\mathcal{O}_L$ and we would like to say something about its rank.
In Dirichlet's unit theorem for number fields over $\mathbb{Q}$, we know that $\mathcal{O}_L^*$ is of rank $r_1+r_2-1$, where $r_1$ is the number of real embeddings and $r_2$ is the number of complex embeddings without conjugates. There are many sources for the case of number fields over $\mathbb{Q}$ but I couldn't find a source for the unit theorem over fields of finite characteristic.


text:
Q: Proper use of coroutines Dispatcher Main and Default I'm trying to do a cup heavy calculation and then want to update the UI.
Below is my code:
private fun updateData() {
        GlobalScope.launch(Dispatchers.Default){ //work on default thread
            while (true){
                response.forEach {
                val out = doIntensiveWork()
                    withContext(Dispatchers.Main){ //update on main thread
                        _data.postValue(out)
                        delay(1500L)
                    }
                }
            }
        }
}

is this way of using coroutines okay? As running the entire work on Main also has no visible effect and work fine.
private fun updateData() {
        GlobalScope.launch(Dispatchers.Main){ //work on Main thread
            while (true){
                response.forEach {
                val out = doIntensiveWork()
                    _data.postValue(out)
                    delay(1500L)
                }
            }
        }
}

Which one is recommended?

A: You should avoid using GlobalScope for the reason described here and here.
And you should consider doing heavy computation off the main thread

suspen fun doHeavyStuff(): Result = withContext(Dispatchers.IO) { // or Dispatchers.Default
 // ...
}

suspend fun waitForHeavyStuf() = withContext(Dispatchers.Main) {
  val result = doHeavyStuff() // runs on IO thread, but results comes back on Main thread
  updateYourUI()
}

Documentation

*

*More about Dispatchers here

*I recommend Roman Elizarov blogs about Kotlin Coroutines


text:
Q: how to export Libgdx project to xcode project using intellij or eclipse? Is there any option to export libgdx ios project to xcode project. i want to add additional functionalities to the game using native code before start the game (like add a screen to display ad or splash screen), so that i need a xcode project.
i unable to find export options for xcode project in libgdx using intellij idea. i can run game directly from intellij idea but unable to export it, anyone can help me?


text:
Q: Changing bootstrap gutter width I need some help with bootstrap gutter width, I've tried almost everything and still can't make bigger space/padding between triangles with i want to make much bigger. Tried adding classes etc..
here's clean code
Media
@media only screen and (max-width : 1200px) {

/* Team */
.team-item .team-triangle {
    width: 90px;
    height: 90px;
}
.team-triangle .content {
    width: 160px;
    height: 160px;
}
.team-hover i {
    margin-top: 50px;
}
.team-hover p {
    font-size: 14px;
}

  /* Medium Devices, Desktops */
  @media only screen and (max-width : 992px) {

/* Team */
.team-item .team-triangle {
    width: 120px;
    height: 120px;
}
.team-triangle .content {
    width: 190px;
    height: 190px;
}
.team-hover i {
    margin-top: 57px;
}
#team-section .col-md-2:nth-child(7n+5),
#team-section .col-md-2:nth-child(7n+1){
    margin-left: 0 !important;
    clear: none !important;
}
#team-section .col-md-2 {
    float: left;
    margin-bottom: 80px;
    width: 33.3333%;
}

HTML
     div class="container">

Plalalal

Jane Doe

John Doe

John Doe

John Doe

CSS
/* ===== Begin team ===== */
.team-item {
height: 130px;
}
.team-item .team-triangle {
width: 130px;
height: 130px;
background: transparent;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
margin: 0 auto;
position: relative;
top: 25px;
box-shadow: 0 0 0 6px #FFFFFF, 0 0 0 7px #dadbdb;
overflow: hidden;
}
.team-item img {
max-width: 100%;
}
.team-items {
margin-bottom: 50px;
padding-top: 0px;
margin-top: 0;

}
.team-triangle .content {
-ms-transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
top: -35px;
position: absolute;
left: -37px;
width: 190px;
height: 190px;
}
.team-hover {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba( 103, 109, 117, 0.9);
opacity: 0;
-webkit-transition: opacity 0.4s ease-in; /* For Safari 3.1 to 6.0 */
transition: opacity 0.4s ease-in;
}
.team-item .team-triangle:hover .team-hover {
opacity: 1;
}
.team-hover i {
color: rgba(255, 255, 255,.75);
font-size: 28px;
margin-top: 57px;
position: relative;
}
.team-hover p {
color: #ffffff;
font-size: 16px;
font-weight: 400;
margin-top: 0;
}
.team-items .col-md-2:nth-child(7n+5) {
clear: left;
margin-left: 24.9999999%;
}
.team-items .col-md-2:nth-child(7n+1) {
clear: left;
margin-left: 16.6666666%;
}
/* ===== End team ===== */

A: Maybe you want something like this.
.large-gutter > [class*='col-'] {
    padding-right:50px;
    padding-left:50px;
}

HTML

        ...

        ...

        ...


text:
Q: How to exchange data between two process?
Possible Duplicate:
IPC Mechanisms in C# - Usage and Best Practices

I have two diffenent process: A and B.
The process A wants to send to the process B some data (array of bytes, strings, structures, etc...). So suppose A need to send the following buffer:
var buffer = new byte[100].
SendToAnotherProcess(B, buffer);

And B need to receive this buffer:
byte[] buffer;
ReceiveFromAnotherProcess(A, out buffer);

What is the easiest solution to do this?

A: You can use Named Pipe. If it is C# 4.0 and above, you can also use Memory mapped file

A: There's a multitude of options. To name a few low-level IPC mechanisms:

*

*named pipes

*shared memory

*TCP/IP sockets

Also, there are some higher-level options:

*

*.NET Remoting

*WCF

A: One common way is to use files to communicate between the processed.
Each can write to a specific file that the other reads from.
You can use WCF, the registry, network interface, message queues or any other mechanism that lives outside the process.

A: There is some special instrument in .net:
.Net Remoting
WCF


text:
Q: ¿Cómo crear un campo password en SQL Server? Quiero crear una tabla usuario para almacenar nombre completo del usuario, nombre del usuario para el sistema y  un password. La duda es: ¿qué tipo de dato debe ser el password para que pueda encriptarlo? Sé que se puede usar varbynary o nvarchar pero no se si exista otro tipo de dato y cual conviene para encriptarlo con php.

A: Usualmente se almacenan contraseñas en un campo común y corriente que tenga la misma longitud que genere el hash que utilizarás para la encriptación. Por ejemplo, si la forma en que encriptarás tu contraseña es con MD5, entonces te conviene crear un char de tamaño 32. Si deseas utilizar SHA1, entonces puedes utilizar un char de 40 (esto es debido a que MD5 y SHA1 siempre generar cadenas de una misma longitud).
Si deseas optimizar espacio, puedes guardar esta información en Binary y haciendo uso de UNHEX puedes convertir los valores para ser leídos y comparados luego desde PHP.
Si deseas saber el tamaño del Binary que debes crear para almacenar con MD5 y SHA1, simplemente divide la longitud del hash de bits entre 8 y obtendrás el resultado.
Por ejemplo:

*

*MD5 = 128-bit -> Binary(16)

*SHA1 = 160-bit -> Binary(20)

Puedes ver una descripción similar a la que te envío en el siguiente enlace:
http://blog.aulaformativa.com/consultorio-desarrollo-web/


text:
Q: Gravity vs inertia As stated according to Newton laws of gravity, every object with mass attracts all other object with a force which produces acceleration.  Basically there are several forces in the universe which affects our planet as well.
My question: can an inertial frame (which has net force zero) can exist in these condition, and does this frame plays any role in producing acceleration?
If two objects are many miles apart and one object has much greater mass then, will the heavier object still accelerate relative to lighter one?

A: Inertial forces are considered non-assigned forces and thus are regarded as fictitious forces (even though they are real and the observer experiences these forces).
They are mostly related to relative motion between (non-inertial, accelerated) frames of reference and transformation(s) thereof (eg centrifugal, Coriolis force, etc.. ).
Apart from that, Newton's gravitation is an inverse square law, which means the gravitational force is diminished by square of distance while being analogous to the masses of objects.
Newtonian Dynamics were based on an absolute space and time. Indeed in Newton's era, there was (and still is) great discussion concerning the centre of the universe which was to be taken as an absolute reference point (for formulating the equations of motion for other systems)
Einstein's special (and general) relativity had an insight on this issue, of absolute reference, whose meaninglessness becomes one of the starting points of SR, GR.
The principle of equivalence, as used by Einstein, in GR (general relativity), actually takes these accelarations (based on non-inertial frames of reference) to be the analog of the graviational field (meaning each such acceleration comes from gravitational field and vice-versa). And this elucidates the equivalence between inertial mass (as used in Newton's 2nd Law of motion) and gravitational mass (as used in Newton;s gravitational law) (which has been experimentally verified up to $10^{-8}$ )
Inertial frame of reference, wikipedia
Absolute space, wikipedia
Newton;s views on space and time, SEP


text:
Q: A hypothetical scenario regarding the pressure exerted by an ideal gas on the walls of a container using kinetic theory This is a question I came across recently :
"1 mole of an ideal gas is contained in a cubical vessel of volume V, ABCDEFGH (these are the vertices of the cube). One of the faces of the cube EFGH is made up of a material which totally absorbs any gas molecules incident on it".
I was asked to determine the relation between the pressure on EFGH and any other face of the cube.
I was able to conclude that it will be half since it is evident from the derivation of the Kinetic Gas Equation and have gotten the right answer but am slightly intrigued by the situation.
Since EFGH is acting as an absorbent, any molecule that collides with that face will no longer be a part of the system. If you consider a large amount of time, you will reach a stage where there are barely any molecules so will the pressure on EFGH still be half of the pressure exerted on any other face?
Thank you.

A: Half seems like the correct answer here. You can visualize this using the fact that the impulse imparted on the other reflecting walls would be double the one imparted on the absorbing wall.
Since the wall absorbs the gas particles, the pressure on all the walls will decrease. However assuming that the motion of gas molecules is completely random, the pressure would still be half of the other walls.


text:
Q: How to determine which TLS/SSL protocol was negotiated when using sslvSSLv23? I am using TIdSSLIOHandlerSocketOpenSSL to open a TLS/SSL connection. I currently want to support tls 1.0 to 1.2.
I initialize the IOHandler like this.
TIdSSLIOHandlerSocketOpenSSL(FSocket.IOHandler).SSLOptions.SSLVersions := [sslvTLSv1_2,sslvTLSv1_1, sslvTLSv1];

After the connection is made, how can I get which protocol was negotiated for the connection? (Both for ensuring the configuration of both the client and test server is correct, and eventually for statistics purpose).
I checked SSLContext.Method after the connection, but it still shows sslvSSLv23 after the connection. SSLContext.SSLVersions shows [sslvTLSv1_2,sslvTLSv1_1, sslvTLSv1].
So how do I get that information?

A: The specific negotiated protocol is in the TIdSSLIOHandlerSocketOpenSSL.SSLSocket.Cipher.Version property after the SSL/TLS session is established.  OpenSSL also has a SSL_get_version() function (which Indy does not use, but you can call directly).


text:
Q: shortcut key for diffing a file in Visual Studio Code? What is the shortcut key for diffing a sourcefile in VSCode?

*

*Seems like I can only do diffs from the Git View

*On top of that I seem to only have the ability to right-click and Open Change, so no seemingly obvious shortcut key from there as well.

Ideally what I would like to do is have the diffing ability on the explorer view or from the git view via shortcut key?

A: With the update to 0.3.0 there is now a command to diff the opened file to another file. You can assign a keybinding to it, the command id is workbench.files.action.compareFileWith

A: There is a special tool for diffing, not sure it answers your question though.
https://visualstudiogallery.msdn.microsoft.com/d8d61cc9-6660-41af-b8d0-0f8403b4b39c


text:
Q: Where does .NET's Debug.Write() output to? I didn't see any output in the console or Visual Studio's output panel from:
Debug.Write("WriteStatements() was reached")

Where does the output go to?

A: Zhaph's answer already told you a way to get to the output of Debug.Write.
Under the hood, the default listener for Debug.Write, i.e. System.Diagnostics.DefaultTraceListener, calls the Windows API function OutputDebugString.
Any message passed to that function can be displayed by a debugger, e.g. you will see the output in the Output window of Visual Studio.
Another quite simple way to see the output of Debug.Write and/or Trace.Write is to use DebugView, a tool from Sysinternals:

DebugView is an application that lets
  you monitor debug output on your local
  system, or any computer on the network
  that you can reach via TCP/IP. It is
  capable of displaying both kernel-mode
  and Win32 debug output, so you don't
  need a debugger to catch the debug
  output your applications or device
  drivers generate, nor do you need to
  modify your applications or drivers to
  use non-standard debug output APIs.

Please note, that Debug.Write statements will not be included in a Release build, hence you would only see the output in the Debug build.

A: It writes to the default trace listener, which you would need to turn on:

Debug.Write Method

If you want this directed to the console you would need to add an instance of the ConsoleTraceListener:
In your .config file ensure you have the following entries:
<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="configConsoleListener"
          type="System.Diagnostics.ConsoleTraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

You may also need to ensure that you've included the /d:TRACE flag when compiling your project to enable the output.


text:
Q: Design studio for mockups and UX designer, iOS, process I just got a new gig with a startup, they have a design studio that creates mock ups in photoshop and then sends them to me ( I am the UX designer ). Now they started talking to me about a process of defining how many pixels are needed for the dimensions of every png and jpeg and all the other mockups and installing photoshop on my machine, so I can figure out the dimensions when I open the psd files.
To me it sounds normal for the design studio to give me some assets and provide a file with every asset and its dimensions ( as in, this is an icon, size is (46x80), as opposed to me opening the asset in psd and figuring that out myself.
I was wondering what do other companies do? What is the process in place between the mock up design studio and the actual UX programmer who translates those assets into actual screens?
Thanks.

A: There is no "standard".  It's generally best to let the designers provide individual files since they're the Photoshop experts and may be tweaking the images over time. You may have to provide them a list of files with descriptions, format, size, and variations (enabled, disabled, active). We ask for retina sizes and then have a tool to generate non-retina ones.
We like to use Google spreadsheets for the list of files and DropBox for the actual transfer.
Having said that, you should have Photoshop and learn to use it because there will be times where a graphic needs a tweak and you don't want to wait on someone else.

A: So who is actually designing the experience? Is it your job to code it? Or, are you the guy that is supposed to come up with the wireframes and then them do the visual design according to that?

A: With the company I work at (and in my freelance work) I'm rarely given the exact sizing of any assets, unless there's a specific requirement.
For the most part, when building a new site (or amending an existing one), I don't find out the sizes of anything until I open up Photoshop and start cropping.


text:
Q: How do I take this integral? How do I take the integral of the Jacobian and show this equality?
I'm thinking of doing it component wise, but I feel that I'm overlooking something simpler.

A: Let's say we have $f:\mathbb{R}^n\to\mathbb{R}^n$ and $g:\mathbb{R}\to\mathbb{R}^n$. Then by chain rule we have that
$$\frac{d}{dt}\Bigr(f(g(t))\Bigr) = J_f(g(t))\cdot g'(t)$$
because the Jacobian is the generalization of $f'$ or the total derivative, in a way that partial derivatives aren't. The crucial difference is that Jacobians will obey the fundamental theorem of calculus under the correct conditions, but arbitrary partials may not.


text:
Q: slice_mut for &mut [T] Why MutableSlice::slice_mut is not implemented for &mut [T]?
Tested on rustc 0.12.0-nightly (b2d4eb186 2014-10-02 15:57:19 +0000):
fn sort<T>(v: &mut [T]){
    let (l, r) = v.split_at_mut(2); // Ok
    let len = v.slice_mut(1u, 3u).len(); // error: type `&mut [T]` does not implement any method in scope named `slice_mut`
}

#[test]
fn it_works() {
    let mut v = [1i, 2, 3, 4, 5, 6];
    sort(v);
}

A: That method had been removed, but the change has since been rolled back. The second line of your sort function compiles right now.


text:
Q: user updated data displays I am trying to find an efficient way to display data based on user input. I have TextView/EditText to obtain the data I need. I want there to be 1 String (name) and 3 Double (rate, amount, time) for a financial calculator.
I want the user to be able to be able to put in anywhere from 1-10 different sets of the same data, but have my displays (TextView) be blank/invisible unless there is data to support them.
I would also like to avoid:
String debtName1, debtName2, debtName3, debtName4, debtName5, debtName6, debtName7, debtName8, debtName9, debtName10;
Double debtRate1, debtRate2, debtRate3, debtRate4, debtRate5, debtRate6, debtRate7, debtRate8, debtRate9, debtRate10;
Double debtBalance1, debtBalance2, debtBalance3, debtBalance4, debtBalance5, debtBalance6, debtBalance7, debtBalance8, debtBalance9, debtBalance10;
Double debtTerm1, debtTerm2, debtTerm3, debtTerm4, debtTerm5, debtTerm6, debtTerm7, debtTerm8, debtTerm9, debtTerm10;

as this seems really stupid. Also, I am planning on having the data be reorganized based on the "Term" so that it is easily displayed from smallest term to largest.
I was considering doing "pointers" but it didn't seem like the Java "work-around" method of pointers would really fit what I'm trying to do.
Any suggestions?

A: what about arrays?
String[] debtNames = new String[10];
Double[] debtRate = new Double[10];

And then populate like this:
debtNames[0] = "someDebitName";

etc...


text:
Q: pycparser.plyparser.ParseError on complex struct I'm trying to use pycparser to parse this C code:
https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c
A repo with a minimal example and Makefile is here:
https://github.com/nbeaver/pycparser-problem
Using pycparser v2.14 (from pip) and gcc 4.9.2 on Debian Jessie.
Things I have tried:

*

*Pass the -nostdinc flag to gcc and including the fake_libc_include folder.

*Use -D'__attribute__(x)=' to take out GCC extensions

*Use fake headers for e.g. <sys/param.h>

*Use the -std=c99 in case the code is not C99 compatible.

*Reproduce the redis example in case there is something weird with my machine.

This is what the traceback looks like:
Traceback (most recent call last):
  File "just_parse.py", line 21, in <module>
    parse(path)
  File "just_parse.py", line 9, in parse
    ast = pycparser.parse_file(filename)
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/__init__.py", line 93, in parse_file
    return parser.parse(text, filename)
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/c_parser.py", line 146, in parse
    debug=debuglevel)
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/ply/yacc.py", line 265, in parse
    return self.parseopt_notrack(input,lexer,debug,tracking,tokenfunc)
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/ply/yacc.py", line 1047, in parseopt_notrack
    tok = self.errorfunc(errtoken)
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/c_parser.py", line 1680, in p_error
    column=self.clex.find_tok_column(p)))
  File "/home/nathaniel/.local/lib/python2.7/site-packages/pycparser/plyparser.py", line 55, in _parse_error
    raise ParseError("%s: %s" % (coord, msg))
pycparser.plyparser.ParseError: in/d_adsc_two_theta.c:63:82: before: .

The traceback points to this line:
https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c#L63
Which in turn points to this #define macro:
https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/mx_motor.h#L484

A: The cause appears to be the offsetof() function. The minimal working examples are fixed by recent commits, however:
https://github.com/eliben/pycparser/issues/87


text:
Q: Python + Selenium + find_element Boa tarde, estou iniciando no Python e estou fazendo um robo de web scraping para um site onde sou obrigado a informar usuário e senha.
Estou utilizando o Selenium e a parte de informar usuário e senha ok, abaixo o codigo já produzido
gecko = "C:\Temp\Projetos\SCRAPER\src\scraper\geckodriver.exe"
binary = FirefoxBinary(r"C:\Program Files\Mozilla Firefox\firefox.exe")
browser = webdriver.Firefox(firefox_binary=binary, executable_path=gecko)

# Variaveis para processamento
url = "https://xxxxxx.xxxxxxx.com.br/sbe-web/login/login.html?modulo=PESSOA_JURIDICA"
usr = "123456"
pwd = "123456"

# Abre o browser
browser.get(url)
browser.implicitly_wait(10)

usuario = browser.find_element_by_name("nomeUsuario")
usuario.clear()
usuario.send_keys(usr)

senha = browser.find_element_by_name("senha")
senha.clear()
senha.send_keys(pwd)

elem = browser.find_element(with_tag_name("input").below(senha)).click

Porém me deparei com um caso onde o elemento que eu preciso clicar é uma imagem que não tem tag/name, já tentei obter o xpath mas ele traz um html gigante, entrei na documentação do Selenium e tentei usar comando bellow(), pois entendi que ele busca o próximo elemento, mas sem sucesso
elem = browser.find_element(with_tag_name("input").below(senha)).click
<td rowspan="2" valign="center">
    <input type="image" src="/sbe-web/especifico/imagens/ok.jpg" tabindex="3">
</td>

Podem me ajudar.

A: Usando Microsoft Edge ou Google Chrome, aperte f12... Irá abrir uma telinha exibindo o código html/css do site em  questão, procure no topo desta telinha dois icones 1 de um mouse clicando em uma telinha e outro de um celular e tela... Click no primeiro e depois clica na imagem em questão, uma parte do código irá ser destacada na telinha de código, aperta com o botão direito nesta parte e copia o Full Xpath.
Agora no seu código digita o seguinte:
elem = browser.find_element_by_xpath("FULL XPATH AQUI !! DENTRO DAS ASPAS DUPLAS").click()
Espero ter ajudado.


text:
Q: Why does my XSD file fail to parse with XML::LibXML? I am trying to validate an XML against schema using LibXML::Schema Validator CPAN module. In that same script am using XML::DOM CPAN module to parse the XML. I want my script to take XML file validate it against XSD and parse it.
When I try to run the script, after validating against xsd it exits and does not parse XML. I want it parse the XML file if it is valid and generate DOM structure. I would really appreciate if someone could share some insights on it.
#usr/bin/perl -w
use XML::LibXML;

my $schema = XML::LibXML::Schema->new(location =>'export.xsd');
my $parser = XML::LibXML->new;

my $xml    = 'Export.xml';
my $doc    = $parser->parse_file($xml);

eval { $schema->validate( $doc ) };
print $@ if $@;

print "$xml is valid\n";

use XML::DOM;
#use strict;

my $parser = new XML::DOM::Parser;
my $doc = $parser->parsefile ("Export.xml");

my $productOfferingnodes = $doc->getElementsByTagName("productOfferings")->item(0);
my @productOffering = $productOfferingnodes->getChildNodes();
    {
        foreach  my $productOffering(@productOffering)
        {
            if ($productOffering->getNodeType == ELEMENT_NODE)
            {
                print $productOffering->getNodeName;
                     }
             }
     }

Error Message:
Schemas parser error : Failed to parse the XML resource 'export.xsd'.

A: Your code is messy. Your script begins with a line which is intended to be the shebang line but is not. You re-define two variables in this short script. You check if validation failed and merrily go on your way even if it did. These are likely not the cause of your problems, but they do make diagnosing the problem harder. I tried to refactor your code. The code below passes perl -c. Further, I tried it using sample XML and XSD files. As explained on that page, with a missing element, validation failed. When the missing information was added, validation succeeded and expected output was produced.
#!/usr/bin/env perl

use strict; use warnings;

use XML::LibXML;
use XML::DOM;

my $xml = 'Export.xml';
my $xsd = 'export.xsd';

if ( my $error = validate_xml_against_xsd($xml, $xsd) ) {
    die "Validation failed: $error\n";
}

my @offerings = get_product_offerings( $xml );
print "$_\n" for @offerings;

sub get_product_offerings {
    my ($xml) = @_;

    my $parser = XML::DOM::Parser->new;
    my $doc = $parser->parsefile($xml);

    my $nodes = $doc->getElementsByTagName("book")->item(0);

    return map {
        $_->getNodeType == ELEMENT_NODE
                         ? $_->getNodeName
                         : ()
    } $nodes->getChildNodes;
}

sub validate_xml_against_xsd {
    my ($xml, $xsd) = @_;

    my $schema = XML::LibXML::Schema->new(location => $xsd);
    my $parser = XML::LibXML->new;

    my $doc = $parser->parse_file($xml);
    eval { $schema->validate( $doc ) };

    if ( my $ex = $@ ) {
        return $ex;
    }
    return;
}

Output:

author
title
genre
price
pub_date
review

By the way, the error message when validation failed was informative: Validation failed: Element 'review': This element is not expected. Expected is (pub_date ).

A: It looks like export.xsd is not a valid XML file. Did you try validating it with another tool? Verify that you have a valid XML file, then worry about the rest of the problem. First things first!

A: Okay, here's some insights:

*

*You're printing "<xml> is valid" whether or not it actually was validated correctly.

*You have a race condition when you check the result of $@. The proper way to do this is:

eval { blah; 1 } or do { die "Encountered error: $@"; }
What error message are you receiving after performing the validation? Is it perhaps Can't locate XML/DOM/Parser.pm in @INC...? You're not doing use XML::DOM::Parser; before calling its constructor.

I want it parse the xml file if it is valid

But you haven't proven that it is: You're getting the error "Schemas parser error : Failed to parse the XML resource 'export.xsd'." Perhaps that indicates that export.xsd is not valid? You shouldn't be trying to call parsefile if the validation failed.


text:
Q: Total Number of pixels in an image How to get the total number of pixel in an image (785x728) image. I have applied loops here and it is taking lot of time. Any easy way
for i=1:height
    for j=1:width
        for d=1:colorChannel
            value = double(rgbImage(i,j,d));
            display(i);
            totalSum = totalSum + value;
            display(totalSum);
        end

    end

end

A: The total number of pixels is not equal to the sum of values in your image.
sumOfAllPixelValues = sum(double(rgbImage(:)));
numberOfPixels      = numel(rgbImage);

The size on disk of an image is numberOfPixels*bytesPerPixel, where bytesPerPixel depends on the bit depth of an image (uint8 would be 8 bits=1 byte, for example.
To downsample the image by half, you can either reduce the bit depth (e.g. going from uint16 to uint8, or you reduce the number of pixels by sqrt(2) in height and width, for example using imresize.


text:
Q: react-native-pdf iOS and Android build errors Tried to create build in iOS and Android. App is using react-native-pdf library. Getting build errors
Error: Unable to resolve module react-native-blob-util from
/Users/runner/work/1/s/node_modules/react-native-pdf/index.js: react-native-blob-util could not be found within the project or in these directories:
node_modules
../../node_modules
We tried adding react-native-blob-util to package.json. But now getting duplicate symbols build error in iOS, because of react-native-blob-util
"react-native-blob-util": "^0.13.16",
"react-native-pdf": "^6.4.0"

A: i get this case too and the best way is

*

*uninstall react-native-blob-util and react-native-pdf

npm uninstall react-native-blob-util
npm uninstall react-native-pdf

*install react-native-pdf version  to 6.2.0

npm install react-native-pdf@6.2.0

*install rn-fetch-blob, or if you already have

npm i rn-fetch-blob

*npm install


text:
Q: jquery $(window).height() not implemented When running the jquery below on document ready, I get a not implemented error on the assignment of top. If that line is removed, the assignment of left works just fine. I'm developing in an IE7 environment. Is this a browser implementation issue?
top = $(window).height();
left = $(window).width();

A: Oh, it has nothing to do with the jQuery code. window.top means something in JavaScript and since you do not delcare var, you are trying to override it! So you should Always scope your variables and if it needs to be global, change your variable name.

A: Put var before the variables.
Because top is == top window.
Credit goes to @travmckinney


text:
Q: Inconsistent Behaviour for Fluent NHibernate Reference Mapping I've been using Fluent NHibernate and I've noticed what I think is inconsistent behaviour when using reference when overloading the default Foreign Key convention.
Following the conventions of NHibernate, I would have a foreign key name with a _ within it and a single record set in each one with a foreign key relationship between the records. For example:
Person
Id - Integer - PK
Name - String/NVarchar

Address
Id - Integer - PK
LineOne - String/NVarchar
Person_Id - Integer - FK

With the following code, this all works as expected
void Main()
{
    using var factory = Fluently.Configure()
        .Database(MsSqliteConfiguration.Standard.UsingFile("C:\\Temp\\Test.db"))
        .Mappings(mappings =>
        {
            mappings
                .FluentMappings
                .AddFromAssemblyOf<AddressClassMap>();
        })
        .BuildSessionFactory();
    using var session = factory.OpenSession();

    session.Query<Address>().ToList().Dump();
}

public class PersonClassMap : ClassMap<Person>
{
    public PersonClassMap()
    {
        Table("Person");

        Id(x => x.Id);
    }
}

public class AddressClassMap : ClassMap<Address>
{
    public AddressClassMap()
    {
        Table("Address");

        Id(x => x.Id);
        Map(x => x.PersonId).Column("Person_Id");

        References(x => x.Person).Not.LazyLoad();
    }
}

public class Person
{
    public virtual int Id { get; set; }
}

public class Address
{
    public virtual int Id { get; set; }

    public virtual int PersonId { get; set; }

    public virtual Person Person { get; set; }
}

Will return the expected data:

However, if I don't follow convention and have no underscore, like so:
Person
Id - Integer - PK
Name - String/NVarchar

Address
Id - Integer - PK
LineOne - String/NVarchar
PersonId - Integer - FK

I would expect, adding a convention for the foreign key like in the below code, would have the same effect but just would work without the underscore:
void Main()
{
    using var factory = Fluently.Configure()
        .Database(MsSqliteConfiguration.Standard.UsingFile("C:\\Temp\\Test.db"))
        .Mappings(mappings =>
        {
            mappings
                .FluentMappings
                .AddFromAssemblyOf<AddressClassMap>()
                .Conventions.Add(FluentNHibernate.Conventions.Helpers.ForeignKey.EndsWith("Id"));
        })
        .BuildSessionFactory();
    using var session = factory.OpenSession();

    session.Query<Address>().ToList().Dump();
}

public class PersonClassMap : ClassMap<Person>
{
    public PersonClassMap()
    {
        Table("Person");

        Id(x => x.Id);
    }
}

public class AddressClassMap : ClassMap<Address>
{
    public AddressClassMap()
    {
        Table("Address");

        Id(x => x.Id);
        Map(x => x.PersonId);

        References(x => x.Person).Not.LazyLoad();
    }
}

public class Person
{
    public virtual int Id { get; set; }
}

public class Address
{
    public virtual int Id { get; set; }

    public virtual int PersonId { get; set; }

    public virtual Person Person { get; set; }
}

However this would yield a exception:

I would expect that this code would allow me to not have to follow the convention of using '_' but this doesn't seem to be the case without hitting the exception. I would expect in the first example, it should be working the same way as the second.
The behavior I desire would be to have the code be like the first example I gave, but not have to follow the convention of NHibernate. This would enable me to have the foreign key ID set on the entity and allow me to persist the relationship using this foreign key property.
I'm unsure if I may have done something wrong or missed something? I've tried various other options of propertyref, etc, to see if it would yield the behaviour I would expect but no avail so far.

A: It doesn't work as expected in first example. It creates 2 columns in Address table for person:

*

*PersonId for References(x => x.Person)

*Person_Id for Map(x => x.PersonId).Column("Person_Id"))

In second example you are trying to map the same column multiple times hence the exception. NHibernate doesn't know how to build INSERT/UPDATE statements for duplicate columns. You need to mark duplicates as read-only properties (as insert="false" update="false" in xml mapping). Something like:
Map(x => x.PersonId);
References(x => x.Person).Not.LazyLoad().ReadOnly();


text:
Q: Batch runas user taskkill I want to make a batch file the runs runas /user:MyUser "taskkill -f -im chrome.exe", but when i execute it it asks me for my password. I want the batch program to automatically insert the password so it does everything by itself. I know I can just execute as admin, writing just the taskkill -f -im chrome.exe part, but i want to do it in that way. Is it possible?

A: You can use the /SaveCred option which will save your credentials the first time you run the command. Subsequent calls will use these cached credentials.
However read this first about the security implications: http://osdir.com/ml/security.ntbugtraq/2003-07/msg00068.html


text:
Q: What happens to my characters if I close my Tera account? Before I spend $50 or more on Tera, I'd like to know what happens to my characters if (when) I decide to quit.  Can I come back at a later time and pick up where I left off or do the characters just get deleted?

A: If you buy the game, play, then cancel your subscription, the characters are retained indefinitely. If you decide to play TERA again after cancelling an account, you'll be able to pick up where you left off.


text:
Q: Gaussian process with independent increments Suppose that we have a continuous Gaussian process $(X_t)_{t \ge 0}$ with independent increments and $X_0=0$. If the increments are also identically distributed, meaning that $X_b-X_a \stackrel{D}{=} X_t-X_s$ whenever $b-a=t-s$, then $\mathbb{E}[X_t]=ct$ and $Cov(X_t,X_s)=\sigma (s \wedge t)$, where $c$ and $\sigma$ are constants.

Let $a(t)=\mathbb{E}[X_t]$. Since $X_0=0$, we have that the function $a$ satisfies $a(t+s)=a(t)+a(s)$, for all $s,t \ge 0$. Also, notice that if $s<t$, then $Cov(X_t,X_s)=Cov((X_t-X_s)+(X_s-X_0),X_s-X_0)=Var(X_s)$. Putting $b(t)=Var(X_t)$ implies by independence that $b(x+y)=b(x)+b(y)$, for all $x,y \ge 0$. So, if we proof that $a(t)$ and $b(t)$ are continuous functions, we are done, since every continuous function $f$ which satisfies the identity $f(u+v)=f(v)+f(u)$ for all $u, v \in \mathbb{R}$ is linear.
So, how can I proof that $\mathbb{E}[X_t]$ and $Var(X_t)$ are continuous functions on $t$?

A: Let $t_0 \in \mathbb{R}$. Since the trajectories are continuous, we have $\lim \limits_{t \to t_0} X_t(\omega)=X_{t_0}(\omega)$. But, we know that the pointwise convergence implies convergence in distribution. By Paul Lévy theorem, for all sequence $(t_k)_{k \ge 1}$ such that $\lim \limits_{k \to \infty}t_k=t_0$, one has
$$\varphi_{X_{t_k}} \to \varphi_{X_{t_0}} \iff X_{t_k} \stackrel{D}{\to} X_{t_0}$$
Then, since $X_t$ is normal distributed for all $t \ge 0$, it follows that $\mathbb{E}[X_{t_k}]\to \mathbb{E}[X_{t_0}] $ and $Var[X_{t_k}]\to Var[X_{t_0}] $. Since this is valid for all sequences $(t_k)_{k \ge 1}$ such that $\lim \limits_{k \to \infty}t_k=t_0$, one can conclude that the functions given by $a(t)=\mathbb{E}[X_t]$ and $b(t)=Var(X_t)$ are continuous in $t$.


text:
Q: Memoization in ASP.NET (worrying about static variables and sessions) I'm starting to use an implementation of memoization in my ASP.NET application, that goes like this (really straightforward, I think):
public static class Memoizer
{
    public static Func<A, B, R> Memoize<A, B, R>(this Func<A, B, R> f)
    {
        var map = new Dictionary<Tuple<A, B>, R>();
        return (a, b) =>
        {
            var tuple = new { a, b };
            R value;
            if (map.TryGetValue(tuple, out value))
                return value;
            value = f(a, b);
            map.Add(tuple, value);
            return value;
        };
    }
}

For 'normal' applications it's all ok, I already tested it, but now I would like to modify this code to be used in an ASP.NET application.
The problem I'm wondering about is that I would need to save the map object in the Session variable, since I don't want different users mix up values/function calls.
Right now, if I Memoize two different functions, with this code I generate two different static variables, and this is ok, but if I save them to the Session, I have to differentiate them for some identifier (function name?), otherwise they would share the same map object in the Session.
I'm a bit puzzled, I don't know if I'm missing something...
Andrea

A: The code that you show is completely thread safe in itself. If you use it like intended and create a function that you don't share with other threads, then it's not a problem.
If you keep the function from one request to the next, then you are not actually using it for memoization, then you are using it for caching.
Using memoization for caching is terrible. The memoized function never forgets anything, so the longer your application runs, the more the map that the function keps will grow. Eventually it can't grow any more because it can't allocate more memory, and the application will crash.
If you want to cache the results, you should use proper caching instead, where the cache can throw away results that hasn't been used in a long time, or when the memory is needed for something else.

A: You cannot save memoized functions in a session.
You need to save each function in some application wide storage:
private static Dictionary<TUser,Fumc<A,B,R>> memoizedfunctions = new Dictionary<TUser,Fumc<A,B,R>>();

Where TUser is some type allowing you to discriminate users (e.g. login name).
By the way,  each user can have more than one initiated session, do you really want them to have separate functions?
You can store maps, not memoized functions, but the idea is the same, you somehow need to tie data to the request.


text:
Q: Is anyone actively developing software to be used with the Emotiv headset? Based on the "featured apps" section of the main page
http://www.emotiv.com/index.php
Alot of the so called "mind control" apps so far seem to be fairly rudimentary read/scan apps that look to profile a certain activity, or perhaps allow the user to manipulate or control an app in a way loosely analogous to using a mouse/keyboard.
I'm just wondering if anyone is currently working on something (assuming they can talk about it) that is a mind blowingly spectacular use of the Emotiv headset?
thanks.

A: Sure. have a look.  The software shown in this video will be out shortly as soon as testing and refining is finished.  It's called EmoLens and it uses the Emotiv EPOC headset to detect emotions and tag Flickr photographs with them.  Note the emotions shown being detected in the video (Happy/Sad/Anger/Fear) have been changed to (Interesting/Happy/Funny):
http://www.youtube.com/watch?v=E9_XZlHoSp0
I'm the author.

*

*roschler


text:
Q: Can't start Jenkins service on Ubuntu I have an Ubuntu server and have installed Jenkins for Continuous Integration on it. I tried to run some builds this morning and they would not run. I looked at the logs and realised that in /var/log/jenkins there were some large log files filling up my hard drive on the server. I deleted these files and attempted to restart Jenkins.
At this point Jenkins will now no longer start. I have had a look at my /tmp directory and it looks like there is some sort of memory leak which is creating a large 1MB file called winstonexxxxxxxxxxx.jar in my tmp directory which fills the entire 1mb space of my tmp directory.
Can anyone help with how to resolve this?
Thanks in advance

A: This is a known issue and has been resolved as 2018-02-14.
Suggested solutions when working with an older Jenkins:

*

*Make sure all Jenkins processes are closed and nothing is running at your Jenkins port (by default 8080)

*Start Jenkins

*Should Jenkins still not start-up, then maybe the 1 MB of /tmp space is the problem. Either enlarge it, or use any of the following solutions to change the temporary directory for Jenkins: How to change the jenkins `/tmp` dir location?

*Should the tmp directory still be filling up, you could install the Tmp Cleaner Plugin.


text:
Q: Where to find condition value when using Add-AzMetricAlertRuleV2 in Azure powershell? I am very new to Azure and currently looking for assistance to help me start my project. Recently I am trying to automate the process of adding alerts for our Azure CosmosDB.
After some research, it looks like I can use Add-AzMetricAlertRuleV2 to add alerts through powershell. According to MS online document I will need to pass $condition to add the rule to the existing ResourceGroup. Where can I get all the existing conditions that I can add to the rule so I can sort out the one that is needed? Some people use  New-AzMetricAlertRuleV2Criteria to assign the value that need to be passed to $condition.  And I can see some example from MS website: https://learn.microsoft.com/en-us/powershell/module/az.monitor/new-azmetricalertrulev2criteria?view=azps-5.0.0
However the above document from MS is not clear to me where I can find the whole list of the name spaces along with the existing criterias that I can add. For example, if I want to add an alert when a new cosmos DB is created on one of the existing ResourceGroup using powershell, where can I check what is the name space I can use to add the new criteria? In another word, where can I find out all the existing conditions with the name space along with them? Thanks,

A: For cosmos DB, the metric namespace will be Microsoft.DocumentDB/databaseAccounts.


text:
Q: Javascript - Async/Await for Dataset to Save in Loop I'm creating a fundraising platform of sorts, but am running into some issues which I believe are caused by Async/await within for loops.
Conceptually, assume I have an array of donation amounts which people have committed. When the code executes, it will a take fundraising goal and loop through the donations, charging any un-charged donation commitments until the commitments are exhausted or the fundraising goal is met. Then the code updates my database to show which new donation commitments were used, or how much of the commitment is available, so they will not be re-charged in the future. This code individually works fine, but if I try to loop it, it causes errors.
I believe the issue is that the future iterations of the loop start executing before the dataset has saved and recognized that some donation commitments were already used. I think I need to have the future iterations of the loop await until the prior is saved?
Is there a proper way to handle this and how would it be done?
Thanks!
for (let i = 0; i < 2; i++) {
    chargeDonations(proj_sub_id, projItem.price, applications.length, project_fees);
}

function chargeDonations(proj_sub_id, price, quantity, fees) {
    wixData.query("Sponsorships")
    .eq("proj_sub_id", proj_sub_id)
    .ne("allFunds", true)
    .find()
    .then( (results) => {
        let sponsorships = results.
        let toCharge = (price + fees);

    for (let i = 0; i < sponsorships.length; i++) {
        let amount_charged = sponsorships[i].amountCharged;
        amount_charged = amount_charged || 0;
        let remaining_sponsorship = (sponsorships[i].amount - amount_charged);
        let net_amount = (remaining_sponsorship - calculateFeesStripePhil(remaining_sponsorship, 1));
        let net_toCharge = (toCharge + calculateFeesStripePhil(toCharge));
        let sponsorships_sum = sponsorships.sum("amount");

    if ((toCharge - net_amount) > 0) {
        console.log("Donation Amount" + remaining_sponsorship);
        console.log("Net Amount" + net_amount);
        toCharge -= net_amount;
        console.log("Still to be Charged: " + toCharge);
        sponsorships_sum -= remaining_sponsorship;

    $w("#dataset2").setFilter( wixData.filter()
        .eq("_id", sponsorships[i]._id))
        .then( () => {
        $w("#dataset2").setFieldValue('amountCharged', (remaining_sponsorship + amount_charged));
        $w("#dataset2").setFieldValue('allFundsUsed', true);
        console.log("Saved Amount Charged");
        $w("#dataset2").save();
        });

        }
     else {
        console.log("Sponsorship Amount " + (toCharge / .921 - 0.3).toFixed(2));
        console.log("Net Amount: " + toCharge);

            $w("#dataset2").setFilter( wixData.filter()
        .eq("_id", sponsorships[i]._id))
        .then( () => {
        $w("#dataset2").setFieldValue('amountCharged', (toCharge + amount_charged));
        console.log("Saved Amount Charged");
        $w("#dataset2").save();
            });
        break;
                }
                }

        });

}

A: YES - you are correct with your assumption that the next loop iteration is called before the previous one has finished.
Use of async/await or maybe Promise.all(/* array of promises*/) should solve this issue.
I believe the proper way would be by doing it in this way:
for (let i = 0; i < 2; i++) {
    await chargeDonations(...);
}

async function chargeDonations(...) {
    ...
}

Furthermore, I would check with WixCode API for which of the functions in the dataset API (e.g. save, setFilter...) and $w API return a Promise and wrap that with async/await block.
Here is something I tried to make you code a bit easier to read and understand:
for (let i = 0; i < 2; i++) {
  await chargeDonations(...);
}

async function filterBySubId(filter){
  /*...*/
}
async function filterBySponsorshipId(filter){
  /*...*/
}

async function chargeDonations(proj_sub_id, price, quantity, fees) {
    const results = await filterBySubId();

    let sponsorships = results;
    let toCharge = (price + fees);

    for (let i = 0; i < sponsorships.length; i++) {
      /* I would also put this block in a function and return values */
      let amount_charged = sponsorships[i].amountCharged;
      amount_charged = amount_charged || 0;
      let remaining_sponsorship = (sponsorships[i].amount - amount_charged);
      let net_amount = (remaining_sponsorship - calculateFeesStripePhil(remaining_sponsorship, 1));
      let net_toCharge = (toCharge + calculateFeesStripePhil(toCharge));
      let sponsorships_sum = sponsorships.sum("amount");
      /* end of calculations block */

      if ((toCharge - net_amount) > 0) {
        console.log("Donation Amount" + remaining_sponsorship);
        console.log("Net Amount" + net_amount);
        toCharge -= net_amount;
        console.log("Still to be Charged: " + toCharge);
        sponsorships_sum -= remaining_sponsorship;

        await filterBySponsorshipId(/* your filter */)

        $w("#dataset2").setFieldValue('amountCharged', (remaining_sponsorship + amount_charged));
        $w("#dataset2").setFieldValue('allFundsUsed', true);
        console.log("Saved Amount Charged");
        await $w("#dataset2").save();

      } else {
        console.log("Sponsorship Amount " + (toCharge / .921 - 0.3).toFixed(2));
        console.log("Net Amount: " + toCharge);

        await filterBySponsorshipId(/* your filter */)
        $w("#dataset2").setFieldValue('amountCharged', (toCharge + amount_charged));
        console.log("Saved Amount Charged");
        await $w("#dataset2").save();
        break;
      }
    }
}

Hope it makes sense to you and helps you,
Cheers!


text:
Q: Borland C++ Typecast overrides - Why Ambiguity? I have the following Enum definition:
typedef enum MyEnumBase
{
  VALUE0 = 0,
  VALUE1,
  VALUE2,
  VALUE3
} MyEnum;

My class uses this enum the following way:
class MyClass {
public:
  MyClass (MyEnum initvalue) {enum1 = initvalue;};
  operator bool() {return (VALUE0 == enum1);};
  operator MyEnum() {return (enum1);};
private:
  MyEnum enum1;
};

With the main function:
int main(int agrc, char *argv[])
{
  MyClass class1 = VALUE2;

  bool OK = (VALUE0 == class1);

  return 0;
}

It compiles with MS VC++ 2010 fine, but Borland XE2 and XE3 tells me the following:
[bcc32 Error] test.cpp(26): E2015 Ambiguity between 'operator MyClass::bool()' and 'operator MyClass::MyEnumBase()'

I guess it could be ambigous - but on the other hand the left side argument is of type MyEnum and it is kind of straight forward to make the enum cast rather than the boolean cast of the class. (As Visual Studio does)
If I swap the arguments (class1 == VALUE0) the problem still persists.
It is possible to modify the line to:
bool OK = (VALUE0 == (MyEnum)class1);

And it would compile, but in that case I would have to go over the whole giant project and "correct" every use of the class - which is not a very good idea since this is our "error variable", it is used excessively.
There must be a more elegant way making this compile. Anyone has an idea?

A: Borland's compiler is clearly wrong here. So whatever you do has to be a workaround for the compiler bug, which makes it annoying, because there's not good "here's the elegant thing you should do" solution: the elegant thing is the thing you're currently doing, and it's triggering the bug. It's rare that there's more than one elegant solution to a problem.
So, the first thing to do is submit a bug report.
Then, one thing you could consider: do you need the conversion to the enum for anything aside from comparisons? If not (or if that case is rare), consider instead overloading the comparison between MyClass and MyEnum.

A: Avoid having a conversion operator and a non(!) explicit constructor taking the same type! explicit MyClass (MyEnum initvalue) enum1(initvalue) {} should fix it.

A: Answer on behalf of tebe:
Since I cannot post the conclusive answer that is more clear to me, I post my thoughts here:
Solution is to overload the global operator == for MyEnum and MyClass arguments.


text:
Q: How to disable DrawerLayout Shadow I am trying to disable the DrawerLayout shadow and i am not finding the relevant answer. can anyone please assist
thanks in advance
i have also tried setDrawerLayout(null,Gravity.Left) but it still does not work

A: mDrawerLayout.setScrimColor(Color.TRANSPARENT);

I'm Assuming that's what you mean. The shadow on the drawers (in between the drawer and the background content) is disabled by default and can be set with the
setDrawerShadow(Drawable shadowDrawable, int gravity)
setDrawerShadow(int resId, int gravity)

functions.

A:
To enable):

mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START)

To disable:

mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.END)

NOTE:
For those who needs perfect drawer shadow, go to link-below and put shadows to your project directory files respectively:
https://developer.android.com/shareables/training/NavigationDrawer.zip

A: To disable the drawer layout shadow, the following line is enough ,
mDrawerLayout.setScrimColor(Color.TRANSPARENT);


text:
Q: Refresh Token gets revoked with Access Token in Laravel Passport I am using laravel/passport password_grant for authentication. The whole generating access_token and refresh_token process is working fine. Now I am trying to use laravel passport token events to revoke old tokens.
I referred to this post for the process -
https://laracasts.com/discuss/channels/laravel/laravel-passport-revoke-and-prune-event-listener-is-not-doing-anything
This works... But when refreshing an access token using the previously provided refresh token, a new access token is being created and also a new refresh token being is created. Eventually, while revoking the old access token, the old, not expired refresh token also gets revoked.
But I think, the refresh token must be revoked only when it has expired.
And also when I remove the EventListeners from the App\Providers\EventServiceProvider $listen array, the revoking mechanism still works.
It's like even pulling out the plug the light bulb is still on.
How to solve this issue? Or am I wrong with the concept somewhere?

A:
But when refreshing an access token using the previously provided refresh token, a new access token is being created and also a new refresh token being is created.

That's basically what makes refresh tokens prevent MITM attacks (to some extent). If someone intercepts your communication and finds your access token, they can impersonate you for as long as it lives. But if they intercept your request to refreshing your tokens, only one of you (the user and the attacker) can use it because it's revoked once used. If you get to use it first, it becomes useless to them. If they use it first, you'll be logged out because your old tokens will be revoked. If they can intercept all your requests - and keep finding your new access tokens, you need to reconsider your security setup.
From RFC6749 section 1.5. Refresh Token under Figure 2: Refreshing an Expired Access Token:

(H)  The authorization server authenticates the client and validates
the refresh token, and if valid, issues a new access token (and,
optionally, a new refresh token).


text:
Q: send ping after post something (for blogs) I want to send some pings after post something to my blog.
As you know wordpress use this method. I coded my own blog system and I want to send pings some web address.
For example I want to request this link.
www.google.com/webmasters/tools/ping?sitemap=http://www.domain.com/sitemap.ashx
http://pingomatic.com/ping/?title=y&blogurl=&rssurl=&chk_weblogscom=on&chk_blogs=on&chk_feedburner=on&chk_syndic8=on&chk_newsgator=on&chk_myyahoo=on&chk_pubsubcom=on&chk_blogdigger=on&chk_blogstreet=on&chk_moreover=on&chk_weblogalot=on&chk_icerocket=on&chk_newsisfree=on&chk_topicexchange=on&chk_google=on&chk_tailrank=on&chk_bloglines=on&chk_postrank=on&chk_skygrid=on&chk_collecta=on&chk_superfeedr=on&chk_audioweblogs=on&chk_rubhub=on&chk_geourl=on&chk_a2b=on&chk_blogshares=on
System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
                    System.Net.NetworkInformation.PingReply prep;

                    string url = "http://www.google.com/webmasters/tools/ping?sitemap=" + sitename + "/sitemap.ashx";

                    prep = p.Send(url);

                    if (prep.Status == System.Net.NetworkInformation.IPStatus.Success)
                    {
                        string address = prep.Address.ToString();
                        string time = prep.RoundtripTime.ToString();
                    }
                    else
                    {
                        string status = prep.Status.ToString();
                    }

This code is not working for me. Any other way?

A: From what I know the ping is done on a computer ip and I see that you call a web page.
Maybe you need to send a web request and not a ping.
Here is an example
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx


text:
Q: Jquery AJAX ($.get or $.ajax) HTML File retrieval, Manipulation, and JSON Send I'm facing an issue where I need to open an html file via Ajax, Modify it, and send it else where via ajax(JSON)
The Below is the HTML file that I'm opening

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Message</title>

Below is the first javascript function I created. This was not working for me because it stripped out the Doctype and html tags of the html document being opened:
function sendEmailFromTemplate(templateLocation) {
    $.get(templateLocation, function (data) {

  data = $(data)
data.find("#test").html("testing")
        data = $('
').append(data.clone()).html()

        $.ajax({ //sends data
            type: "POST",
            url: "secretlocation.aspx",
            data: JSON.stringify({ fromEmail: "test@test.com", fromAbrv: "test", userEmail: $("#txtEmail").val(), message: data }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

            },
            failure: function (response) {
                alert(response.d);
            }
        });
    })

}

Thank you in advanced!

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Message</title>

{message}

function sendEmailFromTemplate(templateLocation) {
    $.get(templateLocation, function (data) {

        data = data.replace(/({message})/g,"Here be my messagem");//putting message

        $.ajax({ //sends data
            type: "POST",
            url: "secretlocation.aspx",
            data: { fromEmail: "test@test.com", fromAbrv: "test", userEmail: $("#txtEmail").val(), message: data },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

            },
            failure: function (response) {
                alert(response.d);
            }
        });
    })
}


text:
Q: How to set longitude and latitude ranges for Bokeh Google Maps plot in Python? I can only set zooms but I need to have a very specific position so I can overlay it over another plot.  How I get a view just from the limits I specified below? Right now I can only set a zoom which is difficult for overlaying on another plot.
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, GMapOptions
from bokeh.plotting import gmap

output_file("gmap.html")

lat_lims = (42.418574999999997, 42.420059000000002)
lon_lims = (-70.907111, -70.904135999999994)
map_options = GMapOptions(lat=np.mean(lat_lims), lng=np.mean(lon_lims), map_type="satellite", zoom=18)

# For GMaps to function, Google requires you obtain and enable an API key:
#
#     https://developers.google.com/maps/documentation/javascript/get-api-key
#
# Replace the value below with your personal API key:
p = gmap(googlemaps_api_key, map_options)

show(p)

A: If you were running a Bokeh Server application, it is possible that the bounds could be returned back to Python in some way, but I'm afraid it is not possible in a standalone Bokeh document (i.e. HTML file) as you have. We are constrained by the using the Google maps API, and the bounds you are asking for are only available once the JavaScript code executes in the browser. The Google API does not accept arbitrary user provided bounds, it only accepts a center/zoom, or a suggested region. The real bounds are only computed and returned (to the browser) by Google API, and are never computed or available in Python.
You might look at the non-google TileProvider plots that are available. Unlike with GMap plots, you yourself can set the map bounds.


text:
Q: How can I debug AWS Cloudfront signed URL access denied? Here is my sign URL function:
private function signUrl($lesson) {
        $cloudFrontClient = AWS::createClient('CloudFront', [
          'region'  => '<my-region>',
          'version' => '2017-03-25'
        ]);

        $streamHostUrl = 'https://<mydomain>.cloudfront.net';
        $resourceKey = $object->s3_video;
        $expires = time() + 300;

        // Create a signed URL for the resource using the canned policy
        $signedUrlCannedPolicy = $cloudFrontClient->getSignedUrl([
            'url'         => $streamHostUrl . '/' . $resourceKey,
            'expires'     => $expires,
            'private_key' => '<MY_PEM_FILE_PATH>',
            'key_pair_id' => '<KEY_PAIR_ID>'
        ]);

        return $signedUrlCannedPolicy;
    }

When clicking on the link I get this ambiguous error message, which can't really help me debug the problem:
 <Error>AccessDenied<Message>Access
 Denied</Message><RequestId>SOME_ID_HERE</RequestId><HostId>SOME_BASE64_HERE_NOT_READABLE</HostId></Error>

I wondered if there is some way to debug this, maybe in the AWS console or some API call?

A: There's more in that error than you see.  Your CloudFront signed URL is actually working.  <HostId> and <RequestId> are not components in an Access Denied error from CloudFront.  This error is coming from S3, after CloudFront accepts your signed request.
In the HTTP response headers, you should see...
Server: Amazon S3
x-amz-request-id: (same value as the XML RequestId)
x-amz-id-2: (same value as the XML HostId)

S3 is not allowing CloudFront to fetch your content.
See Using an Origin Access Identity to Restrict Access to Your Amazon S3 Content and verify your configuration.
Also review the steps in Amazon CloudFront Latency to set your Error Caching Minimim TTL for 403 errors to 0 seconds, otherwise you will continue to see the error for up to 5 minutes (the default) after you fix the issue.
If everything looks correct, you may want to review your S3 bucket logs to ensure that you are requesting the object that you intend to. In CloudFront origin settings, there is a value called Origin Path that should almost always be left blank.  Putting a value there will cause CloudFront to ask for a different object than the URL makes it appear you are requesting, so this value is not commonly something that you should set to anything.

A: try
$signedUrlCannedPolicy = $cloudFrontClient->getSignedUrl([
        'url'  => "{$streamHostUrl} / {$resourceKey}",
        'expires'     => $expires,
        'private_key' => '<MY_PEM_FILE_PATH>',
        'key_pair_id' => '<KEY_PAIR_ID>'
    ]);


text:
Q: How to configure Sub Domain on Kong Ingress Controller We are trying to replicate the existing Traefik configuration with Kong Ingress Controller on Kubernetes cluster.
Currently, I'm trying to configure the sub domain in Kong ingress controller and not sure how exactly to proceed with this.
Below code is from Traefik configuration. Could you please help me configure the similar in Kong.
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: application-xyz
  namespace: default
spec:
  tls: {}
  entryPoints:
    - web
    - websecure
  routes:
    - match: "HostRegexp(`{sub:(www.)?}mycompany.com`) && PathPrefix(`/`)"
      kind: Rule
      priority: 1
      services:
        - name: application-xyz-service
          port: 80

Thanks in Advance.

A: We have explored a bit and found there is no such feature available in kong.  Traefik was a router and it was valid to have this kind of functionality available. We have just configured a couple of ingress rules for www and domain explicitly to achieve this on Kong.
We can also make use of the Admin API available in Kong to achieve the same. The documentation is pretty straight forward on the official site.


text:
Q: HTML site development: div's vs ul's for navigation and menus I'm working on developing a Web 2.0 site, and I've been looking at how sites deal with menus and nav-bars.  Many sites (like twitter) use UL's whereas sites such as stackoverflow use div's that are ID's containing links.
Is there an advantage to not using UL's other than it eliminates some IE bugs?
is there an advantage to using UL's?
Thanks!

A: I personally use ul/li for all of my menu needs as it makes it clear to even an unstyled browser (Links for example) that it is a menu of some sort and that they are various links that lead to different parts on a website.
Not only that, but the markup is remarkably easy and allows for very interesting things to be done using ul, li, and a to make awesome menu's with CSS with various options, CSS sprite backgrounds.
Using divs makes this possible as well, but makes the intent less clear. With a browser that does proper CSS layout you won't notice a difference and the only one that will know is you and the user that does a view-source.
It may make a difference if you need to parse the dom using javascript, it may not...

A: UL's are more friendly to screen-readers, and are a way to force you to keep the menu clean of other html. The li-tags can essentially be handled like divs, if you want that.
So basically the difference is that the ul-tag is a bit more specialized, but can deliver essentially the same thing as divs could.

A: It depends on how you look at it, UL stands for unordered list. Putting things in a UL element is a semantic way of saying the elements children ( <li> ) are list items and therefore a logical group. Which gives the chunk of html more structure/meaning than just a bunch of div tags.
Is a menu a list? I think so. So if you can for something like this prefer the ul.
ul's can be more difficult to style with css, especially when the menu is horizontal.


text:
Q: Cucumber execution stops for execution if initial @then fails for Automation I'm using cucumber framework for the testing. I've three @then conditions, if 1st @then condition gets failed, its not going into second @then condition. How can I overcome?
   @Then("^I check first result$")
public void verifyFirstResult() {
    Assert.assertEquals(results.get("first"), true);    --> This gets failed as its returning false.
}

@Then("^I check second result$")
public void verifySecondResult() {
    Assert.assertEquals(results.get("second"), true);  --> This is not even triggering, the execution stops at the first method itself
}

 @Then("^I check third result$")
public void verifyThirdResult() {
    Assert.assertEquals(results.get("third"), true);
}

How can I overcome this issue?

A: As the steps are written, you cannot overcome this issue. This is how cucumber works. If a step fails, all subsequent steps are skipped until the end of the scenario.
If you want to check multiple conditions in one Then step, you can create a "compound" step that checks multiple conditions, which will cause this one step to fail. This is usually done with a data table:
Then the results should be:
    | Field  | Value |
    | First  | true  |
    | Second | true  |
    | Third  | true  |

References:

*

*https://cucumber.io/docs/gherkin/reference/#data-tables

*https://cucumber.io/docs/cucumber/step-definitions/

A: Could you please clarify the question better?
1) Are you trying to check the three conditions simultaneously, so that the test will fail if any of them (no matter which one) fails?
2) Or are you interested in knowing which particular condition failed in case of error?


text:
Q: Pywinauto: 740, 'CreateProcess', 'The requested operation requires elevation I'm using pywinauto to open thinkorswim
code:
from pywinauto.application import Application
app = Application(backend="uia").start("C:/Program Files/thinkorswim/thinkorswim.exe")

error:
  File "C:\Users\willi\Anaconda3\lib\site-packages\pywinauto\application.py", line 1047, in start
    start_info)             # STARTUPINFO structure.

error: (740, 'CreateProcess', 'The requested operation requires elevation.')

During handling of the above exception, another exception occurred:

A: The error message is clear. You have to run the script as Administrator. In some rare cases it could be additionally solved by changing to 32-bit version of Python or 64-bit version of the app. But running as Administrator is required anyway. Forcing elevation (restarting itself as admin) with disabled UAC (manually in OS settings) is another way, but it can be easily googled in ActiveState recipes.

A: You can do the elevation in windows by finding the IDE executable. In my case it was Pycharm. Right click and select 'Run as Administrator'.


text:
Q: Trying to store numbers in an array and display them by reading from a file I am trying to read the numbers only from a file named Store-1.txt. This file contains the following: "coffee 3Mugs -3Soap 10"
I am using the fscanf() function instead of getc().
My code does not compile. where am I going wrong. PS: I am new to C. please be patient.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[20];
    int i,j;

    FILE *fp;
    fp=fopen("C:/Users/PSN/Desktop/Store-1.txt","r");
    if(fp>0)
    {
        for(i=0;i<4;i++)
        {
            fscanf(fp,"%d",&a[i])
        }
    }
    for(j=0;j<3;j++)
    {
        printf("%d", a[j]);
    }

    fclose(fp);

    system("PAUSE");
    return 0;
}

A: This line is missing a semi-colon.
fscanf(fp,"%d",&a[i])

Should be:
fscanf(fp,"%d",&a[i]);

If you want to read only the numbers in the second column of your file, you can read the first column and just ignore it.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[20];
    int i,j;
    char str[256];

    FILE *fp;
    fp=fopen("C:/Users/PSN/Desktop/Store-1.txt","r");
    if(fp>0)
    {
        for(i=0;i<3;i++)
        {
            fscanf(fp, "%s", str); // read the first column & ignore
            fscanf(fp,"%d",&a[i])
        }
    }
    for(j=0;j<3;j++)
    {
        printf("%d", a[j]);
    }

    fclose(fp);

    system("PAUSE");
    return 0;
}

Note that I changed your loop from 4 to 3 as you have only 3 lines. Better way would be to not hardcode the line read till the end of the file. But that depends on the format of your input file and how many values you want to read etc.

A: Try:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[20];
    int i,j;

    FILE *fp;
    fp=fopen("C:/Users/PSN/Desktop/Store-1.txt","r");
    if(fp>0)
    {
        for(i=0;i<4;i++)
        {
            fscanf(fp,"%d",&a[i]); // <You missed the ; here
        }
    }

    for(j=0;j<3;j++)
    {
        printf("%d", a[j]);
    }

    fclose(fp);

    system("PAUSE");
    return 0;
}

Which is coincidentally a good example of indenting... :-)

A: if your input file, 'store-1.txt', looks like this:
coffee 3
Mugs -3
Soap 10

then try this:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a[20];
    int i;

    FILE *fp;
    fp=fopen("store-1.txt","r");

    if(fp>0) {
        for(i=0;i<3;i++) {
            fscanf(fp,"%*s %d", &a[i]);
        }
    }
    for(i=0;i<3;i++) {
        printf("%d\n", a[i]);
    }

    fclose(fp);

    return 0;
}

should get you heading in the right direction...
note %*s tells fscanf there is a string but to ignore it
an alternative for the intended input:
coffee 3Mugs -3Soap 10

could be:
int main()
{
    int a[20];
    int i,j;

    FILE *fp;
    fp=fopen("store-1.txt","r");

    fscanf(fp, "%*s%d%*s%d%*s%d", word, &a[0], word, &a[1], word, &a[2]);

    /* if(fp>0) { */
    /*     for(i=0;i<3;i++) { */
    /*         fscanf(fp,"%s %d",word, &a[i]); */
    /*     } */
    /* } */
    for(j=0;j<3;j++) {
        printf("%d\n", a[j]);
    }

    fclose(fp);

    return 0;
}

this would work on your input file, but prob not as extensible as you would want it?


text:
Q: I get the message org.openide.filesystems does not exist. Someone else asked this question, but I didn't see anything in the answer that would help me.  Why isn't my netbeans session finding this library?  Thanks for any help.

A: I consulted with an expert at work and found the solution.  I had to add a library dependency for "File System API".  How that relates to an external library is one of the mysteries of netbeans.


text:
Q: Tool to convert regex between different language syntaxes? Is there a tool to convert a regex from one popular language's syntax to another? For example a Python-style regex to a Java-style regex?.
Or at least, has someone put together a set of rules to do these conversions?
And obviously some constructs won't be able to convert.

A: Go to this article, and follow the link to "Regex info's comparison of Regex flavors", that got me to a tool called RegexBuddy, which sounds like it might do what you want.

A: Yes there is a Windows tool that will do this: RegexBuddy


text:
Q: Dart: convert Observable to Future and vice-versa? How can I convert a Dart Observable to a Future and vice-versa?

A: To convert a Observable to a Future:

*

*myObservable.first

*myObservable.firstWhere
To convert a Future to an Observable:

*

*Observable.fromFuture(myFuture)
Or into a simple stream:

*

*myFuture.asStream()


text: Q: Obstruction to lifting homomorphism of groups Is there a "cohomology" group that encodes obstructions to constructing a lift in a diagram of groups below? If $X\to Y$ is an extension and the bottom row is the identity map it's just $H^1(X;\ker(\beta)).$ The answer obviously comes from some obstruction theory arguments, but I can't pinpoint an exact answer. I guess because I don't understand obstruction theory well enough.