problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
No 'Access-Control-Allow-Origin' with header : <p>I have an HTTPS server thah works, I'm trying to return an answer to the client. I am able to send a GET request from the client, but when I return a response from the server, I continue to get this error:</p>
<blockquote>
<p>Failed to load <a href="https://localhost:8000/?uname=user&upass=pass" rel="nofollow noreferrer">https://localhost:8000/?uname=user&upass=pass</a>: Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://localhost:63342" rel="nofollow noreferrer">http://localhost:63342</a>' is therefore not allowed
access.</p>
</blockquote>
<p>What am I doing wrong?</p>
<p>this is my server:</p>
<pre><code>var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8000);
</code></pre>
<p>and this is my client:</p>
<pre><code> const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
};
xhr.open('GET', `https://localhost:8000?uname=${user}&upass=${pass}`,true);
xhr.setRequestHeader("Access-Control-Allow-Origin","*");
xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
xhr.setRequestHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
xhr.setRequestHeader("ccess-Control-Allow-Credentials","true");
xhr.send();
</code></pre>
| 0debug
|
Read data from cloud firestore with firebase cloud function? : <p>I'm an Android developer and recently I've started working on a project based on firebase cloud functions and firestore database. I'm writing an HTTP trigger function that will take two parameters and compare that parameter value with the firestore data value and if the value matches then return a response of true or else false.</p>
<p><strong>Duplicate Question:</strong></p>
<p>Yes, there are some question already asked related to mine but they are not similar:</p>
<ol>
<li><p><a href="https://stackoverflow.com/questions/47522205/firestore-cloud-functions-how-to-read-from-another-document">Firestore + cloud functions: How to read from another document</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/43913139/firebase-http-cloud-functions-read-database-once">Firebase HTTP Cloud Functions - Read database once</a></p></li>
</ol>
<p><strong>Firebase Docs says</strong>: </p>
<blockquote>
<p>Cloud Firestore supports create, update, delete, and write events</p>
</blockquote>
<p>I want to read firestore value from HTTP trigger.</p>
<p><strong>What I have tried:</strong></p>
<pre><code>exports.userData = functions.https.onRequest((req, res) => {
const user = req.query.user;
const pass = req.query.pass;
});
</code></pre>
<p>I'm pretty much stuck at this part. Any help will be greatly appreciated. Thanks</p>
<p>P.S. I have very limited knowledge related to JS/TypeScript/NodeJS</p>
| 0debug
|
static int megasas_init_firmware(MegasasState *s, MegasasCmd *cmd)
{
uint32_t pa_hi, pa_lo;
target_phys_addr_t iq_pa, initq_size;
struct mfi_init_qinfo *initq;
uint32_t flags;
int ret = MFI_STAT_OK;
pa_lo = le32_to_cpu(cmd->frame->init.qinfo_new_addr_lo);
pa_hi = le32_to_cpu(cmd->frame->init.qinfo_new_addr_hi);
iq_pa = (((uint64_t) pa_hi << 32) | pa_lo);
trace_megasas_init_firmware((uint64_t)iq_pa);
initq_size = sizeof(*initq);
initq = cpu_physical_memory_map(iq_pa, &initq_size, 0);
if (!initq || initq_size != sizeof(*initq)) {
trace_megasas_initq_map_failed(cmd->index);
s->event_count++;
ret = MFI_STAT_MEMORY_NOT_AVAILABLE;
goto out;
}
s->reply_queue_len = le32_to_cpu(initq->rq_entries) & 0xFFFF;
if (s->reply_queue_len > s->fw_cmds) {
trace_megasas_initq_mismatch(s->reply_queue_len, s->fw_cmds);
s->event_count++;
ret = MFI_STAT_INVALID_PARAMETER;
goto out;
}
pa_lo = le32_to_cpu(initq->rq_addr_lo);
pa_hi = le32_to_cpu(initq->rq_addr_hi);
s->reply_queue_pa = ((uint64_t) pa_hi << 32) | pa_lo;
pa_lo = le32_to_cpu(initq->ci_addr_lo);
pa_hi = le32_to_cpu(initq->ci_addr_hi);
s->consumer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
pa_lo = le32_to_cpu(initq->pi_addr_lo);
pa_hi = le32_to_cpu(initq->pi_addr_hi);
s->producer_pa = ((uint64_t) pa_hi << 32) | pa_lo;
s->reply_queue_head = ldl_le_phys(s->producer_pa);
s->reply_queue_tail = ldl_le_phys(s->consumer_pa);
flags = le32_to_cpu(initq->flags);
if (flags & MFI_QUEUE_FLAG_CONTEXT64) {
s->flags |= MEGASAS_MASK_USE_QUEUE64;
}
trace_megasas_init_queue((unsigned long)s->reply_queue_pa,
s->reply_queue_len, s->reply_queue_head,
s->reply_queue_tail, flags);
megasas_reset_frames(s);
s->fw_state = MFI_FWSTATE_OPERATIONAL;
out:
if (initq) {
cpu_physical_memory_unmap(initq, initq_size, 0, 0);
}
return ret;
}
| 1threat
|
Name of this CSS syntax? : <p>Can someone please tell me what this syntax is called, I tried looking it up but didn't find it. Im refering to how the player class seems to be extended i.e. ".player:fullscreen". Thank you.</p>
<pre><code>.player {
max-width: 750px; /n
border: 5px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
position: relative;
font-size: 0;
overflow: hidden;
}
/* This css is only applied when fullscreen is active */
.player:fullscreen {
max-width: none;
width: 100%;
}
.player:-webkit-full-screen {
max-width: none;
width: 100%;
}
</code></pre>
| 0debug
|
int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
{
AVCodecContext *const avctx = h->avctx;
H264Context *hx;
int i;
if (h->mb_y >= h->mb_height) {
av_log(h->avctx, AV_LOG_ERROR,
"Input contains more MB rows than the frame height.\n");
return AVERROR_INVALIDDATA;
}
if (h->avctx->hwaccel)
return 0;
if (context_count == 1) {
return decode_slice(avctx, &h);
} else {
for (i = 1; i < context_count; i++) {
hx = h->thread_context[i];
hx->er.error_count = 0;
}
avctx->execute(avctx, decode_slice, h->thread_context,
NULL, context_count, sizeof(void *));
hx = h->thread_context[context_count - 1];
h->mb_x = hx->mb_x;
h->mb_y = hx->mb_y;
h->droppable = hx->droppable;
h->picture_structure = hx->picture_structure;
for (i = 1; i < context_count; i++)
h->er.error_count += h->thread_context[i]->er.error_count;
}
return 0;
}
| 1threat
|
How do you add borderRadius to ImageBackground? : <p>The React Native <code>ImageBackground</code> component is supposed to accept the same prop signature as <code>Image</code>. However, it doesn't seem to accept <code>borderRadius</code>.</p>
<p>This has no affect.</p>
<pre><code><ImageBackground
style={{height: 100, width: 100, borderRadius: 6}}
source={{ uri: 'www.imageislocatedhere.com }}
>
</code></pre>
<p>How do you change the border radius of an <code>ImageBackground</code>?</p>
| 0debug
|
is 0j the square root of -1 in python? : <p>i am a super-beginner-level Python learner. In a tutorial, a guy says that: " The root of -1 in Python is 0j". Is that true? and if true why not 1j? Thanks for attention.</p>
| 0debug
|
Sql server, using or statement condition : I am using a query which its searching inside a table for two conditions. I will give an example:
Select * from Customers where mobile= '" + textboxt1.Text + "' or Phone = '" + textboxt1.Text + "'
The query returns me the first row which mobile or phone numbers is equal with my textbox1.Text.
I need to set a condition: Start looking "entire table" for find the first 'or' statement(mobile). If there is not exist any result then go and search again entire table using the second or condition(Phone).
Is there any easy way which i can write my query? Or i need to use a case for this?
| 0debug
|
Angular4 Components inheritance with abstract class : <p>I want to define a base class for my components to share some features. So i've began with :</p>
<pre><code>export abstract class BaseComponent {
protected getName(): string;
}
@Component(...)
export class MyComponent extends BaseComponent {
protected getName(): string {
return "MyComponent";
}
}
</code></pre>
<p>But after i needed to add some annotations to BaseComponent like <code>@HostListener('window:keydown', ['$event'])</code>. So i had to add <code>@Component</code> to <code>BaseComponent</code> to enable angular annotations. Everything was good... Until i tried to compile in production mode with </p>
<blockquote>
<p>ng build --prod</p>
</blockquote>
<p>:</p>
<blockquote>
<p>Cannot determine the module for class BaseComponent</p>
</blockquote>
<p>So i've added <code>BaseComponent</code> to <code>@NgModule</code>, but i had :</p>
<blockquote>
<p>No template specified for component BaseComponent</p>
</blockquote>
<p>So i've added </p>
<pre><code>@Component({template: ''})
</code></pre>
<p>But i had :</p>
<blockquote>
<p>Argument of type 'typeof BaseComponent' is not assignable to parameter of type 'Type'. Cannot assign an abstract constructor type to a non-abstract constructor type.</p>
</blockquote>
<p>So i had remove the "<code>abstract</code>" keyword to compile in production mode my project.</p>
<p>Do you have a solution? <strong>I dislike bad conception!</strong></p>
| 0debug
|
Overlay everything outside of Div : <p>I found what I was looking for the other day but cannot find it again.</p>
<p>I have a Div with position:aboslute and I'm looking to have a CSS overlay of everything besides that Div.</p>
<p>And if you click that overlay that goes away.</p>
<p>Please help!</p>
| 0debug
|
How do I create a new line with reStructuredText? : <p>How do I force a line break/new line in rst? I don't want it to be a new paragraph (ie. no additional spaces between the lines), I just want the text to start on a new line. Thanks!</p>
| 0debug
|
from collections import Counter
def anagram_lambda(texts,str):
result = list(filter(lambda x: (Counter(str) == Counter(x)), texts))
return result
| 0debug
|
static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
{
int64_t sector_num, end;
BlockDriverState *base = s->base;
BlockDriverState *bs = blk_bs(s->common.blk);
BlockDriverState *target_bs = blk_bs(s->target);
int ret, n;
end = s->bdev_length / BDRV_SECTOR_SIZE;
if (base == NULL && !bdrv_has_zero_init(target_bs)) {
if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, end);
return 0;
}
for (sector_num = 0; sector_num < end; ) {
int nb_sectors = MIN(end - sector_num,
QEMU_ALIGN_DOWN(INT_MAX, s->granularity) >> BDRV_SECTOR_BITS);
mirror_throttle(s);
if (block_job_is_cancelled(&s->common)) {
return 0;
}
if (s->in_flight >= MAX_IN_FLIGHT) {
trace_mirror_yield(s, s->in_flight, s->buf_free_count, -1);
mirror_wait_for_io(s);
continue;
}
mirror_do_zero_or_discard(s, sector_num, nb_sectors, false);
sector_num += nb_sectors;
}
mirror_drain(s);
}
for (sector_num = 0; sector_num < end; ) {
int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
end - sector_num);
mirror_throttle(s);
if (block_job_is_cancelled(&s->common)) {
return 0;
}
ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
if (ret < 0) {
return ret;
}
assert(n > 0);
if (ret == 1) {
bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
}
sector_num += n;
}
return 0;
}
| 1threat
|
java decompiler JD-Gui correctness : <p>Let's say I have a java class A that I want to decompile using JD-GUI. After fixing minor compilation issues (casting and initialize local variable), I compile the decompiled code as class B.</p>
<p>How guarantee is it that class A and class B function the same?</p>
| 0debug
|
Why memset function doesn't work? : <p>Why memset function doesn't work inside c++ function with char pointers?</p>
<pre><code>void change(char* input){
memset(input, 'a', strlen(input));
}
int main(){
char* p = "foo";
cout << p << endl;
change(p);
cout << p << endl;
}
</code></pre>
| 0debug
|
def babylonian_squareroot(number):
if(number == 0):
return 0;
g = number/2.0;
g2 = g + 1;
while(g != g2):
n = number/ g;
g2 = g;
g = (g + n)/2;
return g;
| 0debug
|
Jenkins edit config in multi-branch pipeline : <p>I cannot find a way to edit the configuration of multibranch pipeline projects. When I change to the branch level, there is only a "view configuration" menu item, as opposed to ordinary pipeline projects. </p>
<p>I am looking for a method to configure build triggers from outside Jenkins. My current workaround (define a pipeline per branch) is not feasible beyond initial testing.</p>
| 0debug
|
how to get all html elements in chrome, not source code : i am doing a chrome extension,
in Chrome browser inspect elements, at the bottom will show all elements of the html page.
how can i get all the elements?
the source code not include all elements.
how can i get all elements shown in inspected elements in my chrome extension?
| 0debug
|
grep multiple patterns Or condition on grouping data R : I have a data grouped data,
df <- data.frame(group_id= c(1, 1, 1, 1, 2, 1, 2, 3, 4),
words = c("beach", "sand", "trip", "warm","travel", "water","beach","sand", "trees"),
ID = c("vacation", "vacation", "vacation", "vacation", "meeting","vacation","meeting","onduty", "hiking"))
The group_id is groups of ID column. Now I want to check certain patterns (beach or warm or sand) for each group, and subset only those matching cluster. Any help.
Expected :
id words ID
1 1 beach vacation
2 1 sand vacation
3 1 trip vacation
4 1 warm vacation
5 2 travel meeting
6 1 water vacation
7 2 beach meeting
8 3 sand onduty
| 0debug
|
beautifulsoup : How to I get text from <p> tag in html : <div class="js-match match-list__item result RR" data-match-id="7908"
data-timestamp="1524061800000"
data-team-ids="8,5"
data-venue-id="3">
<p class="result__outcome u-show-phablet">Kolkata Knight Riders won by 7 wickets</p>
<div class="result__teams">
<div class="result__team result__team--loser"> <div class="result__logo u-show-phablet tLogo40x32 t-RR RR"></div>
<div class="result__logo u-hide-phablet tLogo40x RR"></div>
<p class="result__team-name">Rajasthan Royals</p>
<span class="result__score ">
<strong>160</strong>/8
<span class="result__overs">
20/20
</span>
</span>
</div>
<div class="result__links">
<p class="result__outcome u-hide-phablet">Kolkata Knight Riders won by 7 wickets</p>
<p class="result__info u-hide-phablet">
Match 15, 20:00 IST (14:30 GMT), Sawai Mansingh Stadium, Jaipur
</p>
<a class="result__button result__button--mc btn" href="/match/2018/15?tab=scorecard">Match Centre</a>
</div>
<h3 class="match-list__date js-date"><span class="u-font-light">Tuesday</span> 17th April 2018</h3>
<div class="js-match match-list__item result MI" data-match-id="7907"
data-timestamp="1523975400000"
data-team-ids="6,9"
data-venue-id="4">
<p class="result__outcome u-show-phablet">Mumbai Indians won by 46 runs</p>
<div class="result__teams">
<div class="result__team "> <div class="result__logo u-show-phablet tLogo40x32 t-MI MI"></div>
<div class="result__logo u-hide-phablet tLogo40x MI"></div>
<p class="result__team-name">Mumbai Indians</p>
<span class="result__score result__score--winner">
<strong>213</strong>/6
<span class="result__overs">
20/20
</span>
</span>
</div>
How to I fetch the text of all p tags for classes?
````class="result__outcome u-hide-phablet"````
````classs='result__info u-hide-phablet' ````
How do i fetch the text of ````span tag````?
The purpose is to fetch the text of tags i.e. p or span and want to put into a df.
I am fetch it as and it does work
````winner = soup.find_all('p',class_="result__outcome u-hide-phablet")````
````win_list = re.findall(r'>(.*?)</p>', str(winner))````
But when i using it for class ````soup.find_all('p',class_="result__info u-show-phablet"````
it is not working properly.
Please help.
| 0debug
|
"document is not defined" in Nuxt.js : <p>I am trying to use <a href="https://github.com/jshjohnson/Choices" rel="noreferrer">Choices.js</a> within a Vue component. The component compiles successfully, but then an error is triggered:</p>
<blockquote>
<p>[vue-router] Failed to resolve async component default:
ReferenceError: document is not defined</p>
</blockquote>
<p>In the browser I see:</p>
<blockquote>
<p>ReferenceError document is not defined</p>
</blockquote>
<p>I think this has something to do with the SSR in Nuxt.js? I only need Choices.js to run on the client, because it's a client only aspect I guess.</p>
<p><strong>nuxt.config.js</strong></p>
<pre><code>build: {
vendor: ['choices.js']
}
</code></pre>
<p><strong>AppCountrySelect.vue</strong></p>
<pre><code><script>
import Choices from 'choices.js'
export default {
name: 'CountrySelect',
created () {
console.log(this.$refs, Choices)
const choices = new Choices(this.$refs.select)
console.log(choices)
}
}
</script>
</code></pre>
<p>In classic Vue, this would work fine, so I'm very much still getting to grips with how I can get Nuxt.js to work this way.</p>
<p>Any ideas at all where I'm going wrong?</p>
<p>Thanks.</p>
| 0debug
|
Which way to name a function in Go, CamelCase or Semi-CamelCase? : <p>I want to write a function in Go to insert a document into a collection in a MongoDB database. Which way to name the function is better, </p>
<ul>
<li><code>writeToMongoDB</code> or </li>
<li><code>WriteToMongoD</code>? </li>
</ul>
<p>The second is CamelCase, while I saw someone using the style of the first one, so I am not sure which one is more appropriate. Thanks.</p>
| 0debug
|
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
{
int ret, flush = 0;
ret = check_packet(s, pkt);
if (ret < 0)
goto fail;
if (pkt) {
AVStream *st = s->streams[pkt->stream_index];
if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0) {
ret = 0;
goto fail;
}
av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
pkt->size, pkt->dts, pkt->pts);
if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
goto fail;
if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
ret = AVERROR(EINVAL);
goto fail;
}
} else {
av_dlog(s, "av_interleaved_write_frame FLUSH\n");
flush = 1;
}
for (;; ) {
AVPacket opkt;
int ret = interleave_packet(s, &opkt, pkt, flush);
if (pkt) {
memset(pkt, 0, sizeof(*pkt));
av_init_packet(pkt);
pkt = NULL;
}
if (ret <= 0)
return ret;
ret = write_packet(s, &opkt);
if (ret >= 0)
s->streams[opkt.stream_index]->nb_frames++;
av_free_packet(&opkt);
if (ret < 0)
return ret;
}
fail:
av_packet_unref(pkt);
return ret;
}
| 1threat
|
brew installation of Python 3.6.1: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed : <p>I installed python 3.6 using </p>
<p><code>brew install python3</code></p>
<p>and tried to download a file with <code>six.moves.urllib.request.urlretrieve</code> from an https, but it throws the error</p>
<blockquote>
<p>ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)</p>
</blockquote>
<p>In the Python installation (from .pkg), the README indicates that one needs to run the <code>Install Certificates.command</code> after the installation <a href="https://bugs.python.org/msg276516" rel="noreferrer">to</a></p>
<ol>
<li>install <code>certifi</code></li>
<li>symlink the certification path to <code>certify</code> path</li>
</ol>
<p>to be able to use certificates.</p>
<p>However, in brew install, this file does not exist and it does not seem to be run.</p>
| 0debug
|
Kafka doesn't delete old messages in topics : <p>In kafka I have set retention policy to 3 days in <code>server.properties</code></p>
<pre><code>############################# Log Retention Policy #############################
...
log.retention.hours=72
...
</code></pre>
<p>Topics has <code>retention.ms</code> set to <code>172800000</code> (48h).</p>
<p>However, there are still old data in the folder /tmp/kafka-logs and none are being deleted. <em>I waited few hours after changing those properties.</em></p>
<p>Is there something that needs to be set? All topics are being produced to and consumed from currently.</p>
| 0debug
|
static MigrationState *migrate_init(const MigrationParams *params)
{
MigrationState *s = migrate_get_current();
int64_t bandwidth_limit = s->bandwidth_limit;
bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
int64_t xbzrle_cache_size = s->xbzrle_cache_size;
memcpy(enabled_capabilities, s->enabled_capabilities,
sizeof(enabled_capabilities));
memset(s, 0, sizeof(*s));
s->params = *params;
memcpy(s->enabled_capabilities, enabled_capabilities,
sizeof(enabled_capabilities));
s->xbzrle_cache_size = xbzrle_cache_size;
s->bandwidth_limit = bandwidth_limit;
s->state = MIG_STATE_SETUP;
trace_migrate_set_state(MIG_STATE_SETUP);
s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
return s;
}
| 1threat
|
uint32_t nand_getio(DeviceState *dev)
{
int offset;
uint32_t x = 0;
NANDFlashState *s = (NANDFlashState *) dev;
if (!s->iolen && s->cmd == NAND_CMD_READ0) {
offset = (int) (s->addr & ((1 << s->addr_shift) - 1)) + s->offset;
s->offset = 0;
s->blk_load(s, s->addr, offset);
if (s->gnd)
s->iolen = (1 << s->page_shift) - offset;
else
s->iolen = (1 << s->page_shift) + (1 << s->oob_shift) - offset;
}
if (s->ce || s->iolen <= 0)
return 0;
for (offset = s->buswidth; offset--;) {
x |= s->ioaddr[offset] << (offset << 3);
}
if (s->cmd != NAND_CMD_READSTATUS) {
s->addr += s->buswidth;
s->ioaddr += s->buswidth;
s->iolen -= s->buswidth;
}
return x;
}
| 1threat
|
RestSharp post request - Body with x-www-form-urlencoded values : <p>I am using postman and making an api post request where I am adding body with x-www-form-urlencoded key/values and it works fine in postman.</p>
<p>The issue arrises when I try it from c# using RestSharp package.</p>
<p>I have tried the following code below but not getting the response. I get "BadRequest" invalid_client error.</p>
<pre><code>public class ClientConfig {
public string client_id { get; set; } = "value here";
public string grant_type { get; set; } = "value here";
public string client_secret { get; set; } = "value here";
public string scope { get; set; } = "value here";
public string response_type { get; set; } = "value here";
}
public void GetResponse() {
var client = new RestClient("api-url-here");
var req = new RestRequest("endpoint-here",Method.POST);
var config = new ClientConfig();//values to pass in request
req.AddHeader("Content-Type","application/x-www-form-urlencoded");
req.AddParameter("application/x-www-form-urlencoded",config,ParameterType.RequestBody);
var res = client.Execute(req);
return;
}
//Also tried this
req.AddParameter("client_id",config.client_id,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("grant_type",config.grant_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("client_secret",config.client_secret,"application/x-www-form-urlencoded",ParameterType.RequestBody);
req.AddParameter("scope",config.scope,ParameterType.RequestBody);
req.AddParameter("response_type",config.response_type,"application/x-www-form-urlencoded",ParameterType.RequestBody);
//tried this too
var client = new RestClient("url-here");
var req = new RestRequest("endpointhere",Method.POST);
var config = new ClientConfig();
req.AddBody(config);
var res = client.Execute(req);
</code></pre>
| 0debug
|
Tensorflow Serving: When to use it rather than simple inference inside Flask service? : <p>I am serving a model trained using object detection API. Here is how I did it:</p>
<ul>
<li><p>Create a Tensorflow service on port 9000 as described in the <a href="https://www.tensorflow.org/serving/serving_basic" rel="noreferrer">basic tutorial</a></p></li>
<li><p>Create a python code calling this service using predict_pb2 from tensorflow_serving.apis similar to <a href="https://medium.freecodecamp.org/how-to-deploy-an-object-detection-model-with-tensorflow-serving-d6436e65d1d9" rel="noreferrer">this</a></p></li>
<li>Call this code inside a Flask server to make the service available with HTTP</li>
</ul>
<p>Still, I could have done things much easier the following way :</p>
<ul>
<li>Create a python code for inference like in the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb" rel="noreferrer">example in object detection repo</a></li>
<li>Call this code inside a Flask server to make the service available with HTTP</li>
</ul>
<p>As you can see, I could have skipped the use of Tensorflow serving.</p>
<p>So, is there any good reason to use Tensorflow serving in my case ? If not, what are the cases where I should use it ?</p>
| 0debug
|
static int tiff_decode_tag(TiffContext *s, const uint8_t *start,
const uint8_t *buf, const uint8_t *end_buf)
{
unsigned tag, type, count, off, value = 0;
int i, j;
int ret;
uint32_t *pal;
const uint8_t *rp, *gp, *bp;
double *dp;
if (end_buf - buf < 12)
return -1;
tag = tget_short(&buf, s->le);
type = tget_short(&buf, s->le);
count = tget_long(&buf, s->le);
off = tget_long(&buf, s->le);
if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {
av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",
type);
return 0;
}
if (count == 1) {
switch (type) {
case TIFF_BYTE:
case TIFF_SHORT:
buf -= 4;
value = tget(&buf, type, s->le);
buf = NULL;
break;
case TIFF_LONG:
value = off;
buf = NULL;
break;
case TIFF_STRING:
if (count <= 4) {
buf -= 4;
break;
}
default:
value = UINT_MAX;
buf = start + off;
}
} else {
if (count <= 4 && type_sizes[type] * count <= 4) {
buf -= 4;
} else {
buf = start + off;
}
}
if (buf && (buf < start || buf > end_buf)) {
av_log(s->avctx, AV_LOG_ERROR,
"Tag referencing position outside the image\n");
return -1;
}
switch (tag) {
case TIFF_WIDTH:
s->width = value;
break;
case TIFF_HEIGHT:
s->height = value;
break;
case TIFF_BPP:
s->bppcount = count;
if (count > 4) {
av_log(s->avctx, AV_LOG_ERROR,
"This format is not supported (bpp=%d, %d components)\n",
s->bpp, count);
return -1;
}
if (count == 1)
s->bpp = value;
else {
switch (type) {
case TIFF_BYTE:
s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +
((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);
break;
case TIFF_SHORT:
case TIFF_LONG:
s->bpp = 0;
for (i = 0; i < count && buf < end_buf; i++)
s->bpp += tget(&buf, type, s->le);
break;
default:
s->bpp = -1;
}
}
break;
case TIFF_SAMPLES_PER_PIXEL:
if (count != 1) {
av_log(s->avctx, AV_LOG_ERROR,
"Samples per pixel requires a single value, many provided\n");
return AVERROR_INVALIDDATA;
}
if (s->bppcount == 1)
s->bpp *= value;
s->bppcount = value;
break;
case TIFF_COMPR:
s->compr = value;
s->predictor = 0;
switch (s->compr) {
case TIFF_RAW:
case TIFF_PACKBITS:
case TIFF_LZW:
case TIFF_CCITT_RLE:
break;
case TIFF_G3:
case TIFF_G4:
s->fax_opts = 0;
break;
case TIFF_DEFLATE:
case TIFF_ADOBE_DEFLATE:
#if CONFIG_ZLIB
break;
#else
av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");
return -1;
#endif
case TIFF_JPEG:
case TIFF_NEWJPEG:
av_log(s->avctx, AV_LOG_ERROR,
"JPEG compression is not supported\n");
return -1;
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",
s->compr);
return -1;
}
break;
case TIFF_ROWSPERSTRIP:
if (type == TIFF_LONG && value == UINT_MAX)
value = s->avctx->height;
if (value < 1) {
av_log(s->avctx, AV_LOG_ERROR,
"Incorrect value of rows per strip\n");
return -1;
}
s->rps = value;
break;
case TIFF_STRIP_OFFS:
if (count == 1) {
s->stripdata = NULL;
s->stripoff = value;
} else
s->stripdata = start + off;
s->strips = count;
if (s->strips == 1)
s->rps = s->height;
s->sot = type;
if (s->stripdata > end_buf) {
av_log(s->avctx, AV_LOG_ERROR,
"Tag referencing position outside the image\n");
return -1;
}
break;
case TIFF_STRIP_SIZE:
if (count == 1) {
s->stripsizes = NULL;
s->stripsize = value;
s->strips = 1;
} else {
s->stripsizes = start + off;
}
s->strips = count;
s->sstype = type;
if (s->stripsizes > end_buf) {
av_log(s->avctx, AV_LOG_ERROR,
"Tag referencing position outside the image\n");
return -1;
}
break;
case TIFF_TILE_BYTE_COUNTS:
case TIFF_TILE_LENGTH:
case TIFF_TILE_OFFSETS:
case TIFF_TILE_WIDTH:
av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");
return AVERROR_PATCHWELCOME;
break;
case TIFF_PREDICTOR:
s->predictor = value;
break;
case TIFF_INVERT:
switch (value) {
case 0:
s->invert = 1;
break;
case 1:
s->invert = 0;
break;
case 2:
case 3:
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",
value);
return -1;
}
break;
case TIFF_FILL_ORDER:
if (value < 1 || value > 2) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown FillOrder value %d, trying default one\n", value);
value = 1;
}
s->fill_order = value - 1;
break;
case TIFF_PAL:
pal = (uint32_t *) s->palette;
off = type_sizes[type];
if (count / 3 > 256 || end_buf - buf < count / 3 * off * 3)
return -1;
rp = buf;
gp = buf + count / 3 * off;
bp = buf + count / 3 * off * 2;
off = (type_sizes[type] - 1) << 3;
for (i = 0; i < count / 3; i++) {
j = 0xff << 24;
j |= (tget(&rp, type, s->le) >> off) << 16;
j |= (tget(&gp, type, s->le) >> off) << 8;
j |= tget(&bp, type, s->le) >> off;
pal[i] = j;
}
s->palette_is_set = 1;
break;
case TIFF_PLANAR:
if (value == 2) {
av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");
return -1;
}
break;
case TIFF_T4OPTIONS:
if (s->compr == TIFF_G3)
s->fax_opts = value;
break;
case TIFF_T6OPTIONS:
if (s->compr == TIFF_G4)
s->fax_opts = value;
break;
#define ADD_METADATA(count, name, sep)\
if (ret = add_metadata(&buf, count, type, name, sep, s) < 0) {\
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\
return ret;\
}
case TIFF_MODEL_PIXEL_SCALE:
ADD_METADATA(count, "ModelPixelScaleTag", NULL);
break;
case TIFF_MODEL_TRANSFORMATION:
ADD_METADATA(count, "ModelTransformationTag", NULL);
break;
case TIFF_MODEL_TIEPOINT:
ADD_METADATA(count, "ModelTiepointTag", NULL);
break;
case TIFF_GEO_KEY_DIRECTORY:
ADD_METADATA(1, "GeoTIFF_Version", NULL);
ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");
s->geotag_count = tget_short(&buf, s->le);
if (s->geotag_count > count / 4 - 1) {
s->geotag_count = count / 4 - 1;
av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");
}
s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);
if (!s->geotags) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < s->geotag_count; i++) {
s->geotags[i].key = tget_short(&buf, s->le);
s->geotags[i].type = tget_short(&buf, s->le);
s->geotags[i].count = tget_short(&buf, s->le);
if (!s->geotags[i].type)
s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&buf, s->le));
else
s->geotags[i].offset = tget_short(&buf, s->le);
}
break;
case TIFF_GEO_DOUBLE_PARAMS:
dp = av_malloc(count * sizeof(double));
if (!dp) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < count; i++)
dp[i] = tget_double(&buf, s->le);
for (i = 0; i < s->geotag_count; i++) {
if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {
if (s->geotags[i].count == 0
|| s->geotags[i].offset + s->geotags[i].count > count) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
} else {
char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");
if (!ap) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
av_freep(&dp);
return AVERROR(ENOMEM);
}
s->geotags[i].val = ap;
}
}
}
av_freep(&dp);
break;
case TIFF_GEO_ASCII_PARAMS:
for (i = 0; i < s->geotag_count; i++) {
if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {
if (s->geotags[i].count == 0
|| s->geotags[i].offset + s->geotags[i].count > count) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);
} else {
char *ap = av_malloc(s->geotags[i].count);
if (!ap) {
av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");
return AVERROR(ENOMEM);
}
memcpy(ap, &buf[s->geotags[i].offset], s->geotags[i].count);
ap[s->geotags[i].count - 1] = '\0';
s->geotags[i].val = ap;
}
}
}
break;
default:
av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",
tag, tag);
}
return 0;
}
| 1threat
|
Is Sql server express edition 2014 expire? : <p>I am using SqlServer Express edition 2014 for office purpose. I'm using it since 6 months, but I couldn't found any expiry alert. Could you please suggest I can use it for permanently or will it be expired? </p>
<p>Please let us know how to know expiry date. Thanks.</p>
| 0debug
|
Is it possible to apply a CSS style to the container element? : <p>I am looking for a selector which applies to any div element that contains an element identified by the p.my selector</p>
<pre><code><div>
<p class="my">
prova
</p>
</div>
</code></pre>
| 0debug
|
Filtering object by keys in lodash : <p>I wrote the function below to return all keys in an object that match a specific pattern. It seems really round-about because there's no filter function in lodash for objects, when you use it all keys are lost. Is this the only way to filter an objects keys using lodash? </p>
<pre><code>export function keysThatMatch (pattern) {
return (data) => {
let x = _.chain(data)
.mapValues((value, key) => {
return [{
key: key,
value: value
}]
})
.values()
.filter(data => {
return data[0].key.match(pattern)
})
.zipWith(data => {
let tmp = {}
tmp[data[0].key] = data[0].value
return tmp
})
.value()
return _.extend.apply(null, x)
}
}
</code></pre>
| 0debug
|
Get unlimited char in Cpp : <p>I want to get unlimited chars, actually I created char*, I use cin for it, and I want to change it to string.
I don't know the length of the input which user enters, so I made this solution for myself.
Can someone tell me plz, how to get a char* without knowing the size of input and converting to string.
thanks. </p>
| 0debug
|
My c output always 0 : <p>When i run this c program to calculate BMI, the output i get is always 0
can i know whats the problem? i am able to get the value of w and h but it seems bmi keeps returning 0 as the result</p>
<pre><code>#include <stdio.h>
int main()
{
float w, h, bmi;
printf("please enter your weight in kg");
scanf("%d", &w);
printf("please enter your height in m");
scanf("%d", &h);
bmi = (w/(h*h));
printf("Your BMI is %d\n", bmi);
return 0;
}
</code></pre>
| 0debug
|
static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
const float lambda)
{
int start = 0, i, w, w2, g;
float M[128], S[128];
float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
SingleChannelElement *sce0 = &cpe->ch[0];
SingleChannelElement *sce1 = &cpe->ch[1];
if (!cpe->common_window)
return;
for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
for (g = 0; g < sce0->ics.num_swb; g++) {
if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
float dist1 = 0.0f, dist2 = 0.0f;
for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
float minthr = FFMIN(band0->threshold, band1->threshold);
float maxthr = FFMAX(band0->threshold, band1->threshold);
for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
M[i] = (sce0->coeffs[start+w2*128+i]
+ sce1->coeffs[start+w2*128+i]) * 0.5;
S[i] = M[i]
- sce1->coeffs[start+w2*128+i];
}
abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
L34,
sce0->ics.swb_sizes[g],
sce0->sf_idx[(w+w2)*16+g],
sce0->band_type[(w+w2)*16+g],
lambda / band0->threshold, INFINITY, NULL);
dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
R34,
sce1->ics.swb_sizes[g],
sce1->sf_idx[(w+w2)*16+g],
sce1->band_type[(w+w2)*16+g],
lambda / band1->threshold, INFINITY, NULL);
dist2 += quantize_band_cost(s, M,
M34,
sce0->ics.swb_sizes[g],
sce0->sf_idx[(w+w2)*16+g],
sce0->band_type[(w+w2)*16+g],
lambda / maxthr, INFINITY, NULL);
dist2 += quantize_band_cost(s, S,
S34,
sce1->ics.swb_sizes[g],
sce1->sf_idx[(w+w2)*16+g],
sce1->band_type[(w+w2)*16+g],
lambda / minthr, INFINITY, NULL);
}
cpe->ms_mask[w*16+g] = dist2 < dist1;
}
start += sce0->ics.swb_sizes[g];
}
}
}
| 1threat
|
R: Reading multiple .dat files as a list and saving as .RDATA files : I want to import multiple `.DAT` files from a directory and make them as a list elements and then save them as `.RDATA` files.
I tried the following code
files <- dir(pattern = "*.DAT")
library(tidyverse)
Data1 <-
files %>%
map(~ read.table(file = ., fill = TRUE))
which works sometimes and fails others. The files are also available on [this link][1]. I want to read all files and them save them as `.RDATA` with the same names. Any help will be highly appreciated. Thanks
[1]: https://www2.stat.duke.edu/courses/Spring03/sta113/Data/Hand/Hand.html
| 0debug
|
Get key value pair from json string in c# : I have a json string like
{["EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"],["EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"]
}
I have serialized and got an object array.
Could anyone help me to get the key value pair from these object array.
| 0debug
|
Vue js interpolation values sum : There exist any way in Vue js to make a sum between two interpolation values inside an html tag?
ex:
value1= 5
value2= 3
<span> {{value1}} + {{value2}}</span>
So I would like to know if its posible to obtain a third value rendered on the _span_ tag adding the two values.
| 0debug
|
Can't connect to database inside file triggered using AJAX : I'm using AJAX to trigger my validation.php file. I want to connect to my database in that file, so I included connect.php file but it's causing some problem.
<script type="text/javascript">
$(document).ready(function(){
$("#offer-form").submit(function(e){
e.preventDefault();
$.ajax({
type : 'POST',
data: {
'name': $('#name-input').val()
},
url : 'validation.php',
success : function(data) {
$("#name-error").text(data["name-error"]);
}
});
return false;
});
})
</script>
validation.php
<?php
header('Content-Type: application/json');
$error = array("name-error" => "");
require_once "connect.php";
$error['name-error'] = "error";
echo json_encode($error);
?>
connect.php
<?php
$serverName = "localhost";
$dbName = "test";
$username = "root";
$password = "";
try
{
$conn = new PDO("mysql:host=$serverName; dbname=$dbName",
$username,
$password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
echo "Connected successfully";
}
catch (PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I simplified my code. The thing is that using *require_once* inside my validation.php file causes *name-error* no to be displayed. Another strange thing to me is that this file works when I type .../validation.php in my browser. I'm already using connect.php in my main file (one including script shown above) and it works fine.
| 0debug
|
React Native BUILD SUCCEED, but "No devices are booted." : <p>Here's my environment:</p>
<pre>
➜ AwesomeProject node --version
v6.3.0
➜ AwesomeProject npm --version
3.10.3
➜ AwesomeProject react-native --version
react-native-cli: 1.0.0
react-native: 0.29.0
➜ AwesomeProject watchman --version
3.0.0
</pre>
<p><code>Xcode version 7.3.1</code></p>
<p>I created the <code>AwesomeProject</code> described on: <a href="https://facebook.github.io/react-native/docs/getting-started.html#content">https://facebook.github.io/react-native/docs/getting-started.html#content</a></p>
<p>Then execute: <code>sudo react-native run-ios</code></p>
<p>Here's what I'm getting:</p>
<pre>
...
export SYSTEM_DEVELOPER_USR_DIR=/Applications/Xcode.app/Contents/Developer/usr
export SYSTEM_DEVELOPER_UTILITIES_DIR=/Applications/Xcode.app/Contents/Developer/Applications/Utilities
export SYSTEM_DOCUMENTATION_DIR=/Library/Documentation
export SYSTEM_KEXT_INSTALL_PATH=/System/Library/Extensions
export SYSTEM_LIBRARY_DIR=/System/Library
export TAPI_VERIFY_MODE=ErrorsOnly
export TARGETED_DEVICE_FAMILY=1
export TARGETNAME=AwesomeProject
export TARGET_BUILD_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Products/Debug-iphonesimulator
export TARGET_DEVICE_MODEL=iPhone7,2
export TARGET_DEVICE_OS_VERSION=9.3
export TARGET_NAME=AwesomeProject
export TARGET_TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
export TEMP_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
export TEMP_FILES_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
export TEMP_FILE_DIR=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build
export TEMP_ROOT=/Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates
export TOOLCHAINS=com.apple.dt.toolchain.XcodeDefault
export TOOLCHAIN_DIR=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
export TREAT_MISSING_BASELINES_AS_TEST_FAILURES=NO
export UID=0
export UNLOCALIZED_RESOURCES_FOLDER_PATH=AwesomeProject.app
export UNSTRIPPED_PRODUCT=NO
export USER=root
export USER_APPS_DIR=/var/root/Applications
export USER_LIBRARY_DIR=/var/root/Library
export USE_DYNAMIC_NO_PIC=YES
export USE_HEADERMAP=YES
export USE_HEADER_SYMLINKS=NO
export VALIDATE_PRODUCT=NO
export VALID_ARCHS="i386 x86_64"
export VERBOSE_PBXCP=NO
export VERSIONPLIST_PATH=AwesomeProject.app/version.plist
export VERSION_INFO_BUILDER=root
export VERSION_INFO_FILE=AwesomeProject_vers.c
export VERSION_INFO_STRING="\"@(#)PROGRAM:AwesomeProject PROJECT:AwesomeProject-\""
export WRAPPER_EXTENSION=app
export WRAPPER_NAME=AwesomeProject.app
export WRAPPER_SUFFIX=.app
export WRAP_ASSET_PACKS_IN_SEPARATE_DIRECTORIES=NO
export XCODE_APP_SUPPORT_DIR=/Applications/Xcode.app/Contents/Developer/Library/Xcode
export XCODE_PRODUCT_BUILD_VERSION=7D1014
export XCODE_VERSION_ACTUAL=0731
export XCODE_VERSION_MAJOR=0700
export XCODE_VERSION_MINOR=0730
export XPCSERVICES_FOLDER_PATH=AwesomeProject.app/XPCServices
export YACC=yacc
export arch=x86_64
export diagnostic_message_length=124
export variant=normal
/bin/sh -c /Users/glaksmono/Documents/React/AwesomeProject/ios/build/Build/Intermediates/AwesomeProject.build/Debug-iphonesimulator/AwesomeProject.build/Script-00DD1BFF1BD5951E006B06BC.sh
Skipping bundling for Simulator platform
=== BUILD TARGET AwesomeProjectTests OF PROJECT AwesomeProject WITH CONFIGURATION Debug ===
Check dependencies
** BUILD SUCCEEDED **
Installing build/Build/Products/Debug-iphonesimulator/AwesomeProject.app
No devices are booted.
Launching org.reactjs.native.example.AwesomeProject
No devices are booted.
</pre>
<p>And the iOS iPhone 6 simulator is just showing a black screen.</p>
<p>Ideas?</p>
| 0debug
|
Mocking globals in Jest : <p>Is there any way in Jest to mock global objects, such as <code>navigator</code>, or <code>Image</code>*? I've pretty much given up on this, and left it up to a series of mockable utility methods. For example:</p>
<pre><code>// Utils.js
export isOnline() {
return navigator.onLine;
}
</code></pre>
<p>Testing this tiny function is simple, but crufty and not deterministic at all. I can get 75% of the way there, but this is about as far as I can go:</p>
<pre><code>// Utils.test.js
it('knows if it is online', () => {
const { isOnline } = require('path/to/Utils');
expect(() => isOnline()).not.toThrow();
expect(typeof isOnline()).toBe('boolean');
});
</code></pre>
<p>On the other hand, if I am okay with this indirection, I can now access <code>navigator</code> via these utilities:</p>
<pre><code>// Foo.js
import { isOnline } from './Utils';
export default class Foo {
doSomethingOnline() {
if (!isOnline()) throw new Error('Not online');
/* More implementation */
}
}
</code></pre>
<p>...and deterministically test like this...</p>
<pre><code>// Foo.test.js
it('throws when offline', () => {
const Utils = require('../services/Utils');
Utils.isOnline = jest.fn(() => isOnline);
const Foo = require('../path/to/Foo').default;
let foo = new Foo();
// User is offline -- should fail
let isOnline = false;
expect(() => foo.doSomethingOnline()).toThrow();
// User is online -- should be okay
isOnline = true;
expect(() => foo.doSomethingOnline()).not.toThrow();
});
</code></pre>
<p>Out of all the testing frameworks I've used, Jest feels like the most complete solution, but any time I write awkward code just to make it testable, I feel like my testing tools are letting me down.</p>
<p>Is this the only solution or do I need to add Rewire?</p>
<p>*Don't smirk. <code>Image</code> is fantastic for pinging a remote network resource.</p>
| 0debug
|
Make a protocol conform to another protocol : <p>I have two protocols: <em>Pen</em> and <em>InstrumentForProfessional</em>. I'd like to make any <em>Pen</em> to be an <em>InstrumentForProfessional</em>:</p>
<pre><code>protocol Pen {
var title: String {get}
var color: UIColor {get}
}
protocol Watch {} // Also Instrument for professional
protocol Tiger {} // Not an instrument
protocol InstrumentForProfessional {
var title: String {get}
}
class ApplePen: Pen {
var title: String = "CodePen"
var color: UIColor = .blue
}
extension Pen: InstrumentForProfessional {} // Unable to make ApplePen an Instument for Professional: Extension of protocol Pen cannot have an inheritance clause
let pen = ApplePen() as InstrumentForProfessional
</code></pre>
| 0debug
|
static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)
{
if (arm_feature(env, ARM_FEATURE_LPAE)) {
env->cp15.par_el1 = value;
} else if (arm_feature(env, ARM_FEATURE_V7)) {
env->cp15.par_el1 = value & 0xfffff6ff;
} else {
env->cp15.par_el1 = value & 0xfffff1ff;
}
}
| 1threat
|
What is wrong with this query I am new : I want to query MySql database in MSSQL using linked server however I keep getting this error:
***Msg 102, Level 15, State 1, Procedure uspGetTimeLog, Line 16
Incorrect syntax near '+'.***
Here is the sql code below
SELECT * FROM OPENQUERY([MYSQLCONN],
'SELECT e_id, TDate, Entry, `Exit` FROM timemgt.daymaster
WHERE TDate >= ''''' + @frmDate + ''''' ')
| 0debug
|
How to clean Docker container logs? : <p>I read my Docker container log output using </p>
<pre><code>docker logs -f <container_name>
</code></pre>
<p>I log lots of data to the log in my node.js app via calls to <code>console.log()</code>. I need to clean the log, because it's gotten too long and the <code>docker logs</code> command first runs through the existing lines of the log before getting to the end. How do I clean it to make it short again? I'd like to see a command like:</p>
<pre><code>docker logs clean <container_name>
</code></pre>
<p>But it doesn't seem to exist.</p>
| 0debug
|
string in a sequence in python : <p>I am solving a problem in codechef which is </p>
<blockquote>
<p>Chef has a sequence of N numbers. He like a sequence better if the sequence contains his favorite sequence as a substring.
Given the sequence and his favorite sequence(F) check whether the favorite sequence is contained in the sequence</p>
<p>Input</p>
<p>The first line will contain the number of test cases and are followed
by the cases. Each test case consists of four lines: The length of
the sequence, the sequence N,the length of F and the sequence F </p>
<p>Output</p>
<p>Print "Yes" if the sequence contains the favourite sequence int it
otherwise print "No" Constraints</p>
</blockquote>
<pre><code>1<=T<=10
1 1
Input:
2
6
1 2 3 4 5 6
3
2 3 4
6
22 5 6 33 1 4
2
4 15
Output:
Yes
No
</code></pre>
<p>to this I wrote
`</p>
<pre><code>for _ in xrange(int(raw_input())):
raw_input()
s = raw_input()
raw_input()
f = raw_input()
print "Yes" if f in s else "No"`
</code></pre>
<p>it returns correct result (as far as I have checked ) bu the grader returns wrong. why is this wrong ?</p>
| 0debug
|
static void *mptsas_load_request(QEMUFile *f, SCSIRequest *sreq)
{
SCSIBus *bus = sreq->bus;
MPTSASState *s = container_of(bus, MPTSASState, bus);
PCIDevice *pci = PCI_DEVICE(s);
MPTSASRequest *req;
int i, n;
req = g_new(MPTSASRequest, 1);
qemu_get_buffer(f, (unsigned char *)&req->scsi_io, sizeof(req->scsi_io));
n = qemu_get_be32(f);
#ifdef NDEBUG
#error building with NDEBUG is not supported
#endif
assert(n >= 0);
pci_dma_sglist_init(&req->qsg, pci, n);
for (i = 0; i < n; i++) {
uint64_t base = qemu_get_be64(f);
uint64_t len = qemu_get_be64(f);
qemu_sglist_add(&req->qsg, base, len);
}
scsi_req_ref(sreq);
req->sreq = sreq;
req->dev = s;
return req;
}
| 1threat
|
void qemu_set_cloexec(int fd)
{
int f;
f = fcntl(fd, F_GETFD);
fcntl(fd, F_SETFD, f | FD_CLOEXEC);
}
| 1threat
|
Erro na busca sql, preciso de ajuda para fazer a busca : Ola, estou tendo dificuldade para fazer uma consulta seletiva usando duas tabelas, provavelmente estou errando a sintaxe da busca, agradeço caso alguem possa me passar a forma correta de fazer a busca.
ara testes criei 4 perguntas,apos responder as 4 deveria direcionar para uma pagina dizendo que nao ha mais perguntas.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<?php
$sqluser = "SELECT a.aquestion_id, a.user_id, b.pergunta, b.question_id FROM respostas a INNER JOIN questions b ON a.aquestion_id != b.question_id WHERE a.user_id = '$logado' ORDER BY RAND() LIMIT 1";
$executarquest=mysqli_query($conuser, $sqluser);
while ($exibir = mysqli_fetch_array($executarquest)){
if ($exibir['question_id'] > 0)
{
$guarda = ($exibir['question_id']);
echo '<b>Quesion ID: </b>';
echo $exibir['question_id'];
echo '<br>';
echo $exibir['pergunta'];
echo $exibir['user_id'];
}
else{
header('location:/quiz/acabou.php');
}
}
?>
<!-- end snippet -->
Estou tentando criar uma serie de perguntas para ajudar meu filho na escola, uma especie de licao de casa mas nao estou conseguindo...
Agradeco qualquer ajuda.
| 0debug
|
How can I dial the phone from Flutter? : <p>I am building a Flutter app, and I'd like to dial a phone number in response to a button tap. What's the best way to do this?</p>
<p>Thanks!</p>
| 0debug
|
What does docker mean when it says "Memory limited without swap" : <p>I'm getting a warning when I run docker:</p>
<blockquote>
<p>WARNING: Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.</p>
</blockquote>
<p>I'm trying to work out what this means, particularly the phrase "Memory limited without swap."</p>
<p>Does this mean that the container can use more memory than you would normally allow it by using the swap space of the host machine? Or does it mean that the container can't use the swap space, even when the host runs out of memory completely? Is it caused by having no swap space configured? Is it irrelevant if you aren't using swap anyway?</p>
<p>Note: I'm not interested in how to fix it - there are lots of results about that on google. I'm interested in what it <em>means</em>, and why it matters.</p>
| 0debug
|
Google Map activity will not support in Android Studio 3.0.1 API 24 : I am learner to Android.I desire to develop Location Tracker Application using google map on Android Studio 3.0.1.Therefore, I have been selected google map activity for XML.
But It is not supported.The error like [All imported classes are in error mode ] [1]
[all methods are in red and Gradle sync failed ][2]
[1]: https://i.stack.imgur.com/Io20N.png
[2]: https://i.stack.imgur.com/BYyjS.png
Can anyone give the suggestion.
| 0debug
|
C# slow drawing a lot of lines : I want to draw a lot of lines in 3 forms, but when i call this (code):
the form spend a lot of time, with 200+ lines spend 1 sec aprox, what i doing wrong?
public void drawObjects()
{
pAux = selectedPen;
for (int i = 0; i < objects.Count; i++)
{
for(int ed = 0; ed < objects[i].getEdges().Count; ed++)
{
frontGraphics.DrawRectangle(recPen, (objects[i].getEdges()[ed].getPoint1().X + 332), -(objects[i].getEdges()[ed].getPoint1().Y - 170), 2, 2);
rightGraphics.DrawRectangle(recPen, objects[i].getEdges()[ed].getPoint1().Z + 332, -(objects[i].getEdges()[ed].getPoint1().Y - 170), 2, 2);
topGraphics.DrawRectangle(recPen, objects[i].getEdges()[ed].getPoint1().X + 332, -(objects[i].getEdges()[ed].getPoint1().Z - 170), 2, 2);
if (objects[i].getEdges().Count > 0)
{
if (objects[i].selected == true)
pAux = selectedPen;
else
pAux = linePen;
frontGraphics.DrawLine(pAux, objects[i].getEdges()[ed].getPoint1().X + 332, -(objects[i].getEdges()[ed].getPoint1().Y -170),
objects[i].getEdges()[ed].getPoint2().X + 332, -(objects[i].getEdges()[ed].getPoint2().Y -170));
rightGraphics.DrawLine(pAux, objects[i].getEdges()[ed].getPoint1().Z + 332, -(objects[i].getEdges()[ed].getPoint1().Y - 170),
objects[i].getEdges()[ed].getPoint2().Z + 332, -(objects[i].getEdges()[ed].getPoint2().Y - 170));
topGraphics.DrawLine(pAux, objects[i].getEdges()[ed].getPoint1().X + 332, -(objects[i].getEdges()[ed].getPoint1().Z - 170),
objects[i].getEdges()[ed].getPoint2().X + 332, -(objects[i].getEdges()[ed].getPoint2().Z - 170));
}
}
}
}
| 0debug
|
static int vmdk_open_vmdk3(BlockDriverState *bs,
BlockDriverState *file,
int flags)
{
int ret;
uint32_t magic;
VMDK3Header header;
VmdkExtent *extent;
ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));
if (ret < 0) {
return ret;
}
extent = vmdk_add_extent(bs,
bs->file, false,
le32_to_cpu(header.disk_sectors),
le32_to_cpu(header.l1dir_offset) << 9,
0, 1 << 6, 1 << 9,
le32_to_cpu(header.granularity));
ret = vmdk_init_tables(bs, extent);
if (ret) {
vmdk_free_last_extent(bs);
}
return ret;
}
| 1threat
|
3D ploting of points : I want to use python to plot some specific points in 3D given their coordinates. I want to use the matplotlib library but I'm not sure if there's an easy way of doing this.
Thanks for your time.
| 0debug
|
static int estimate_qp(MpegEncContext *s, int dry_run){
if (s->next_lambda){
s->current_picture_ptr->quality=
s->current_picture.quality = s->next_lambda;
if(!dry_run) s->next_lambda= 0;
} else if (!s->fixed_qscale) {
s->current_picture_ptr->quality=
s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
if (s->current_picture.quality < 0)
return -1;
}
if(s->adaptive_quant){
switch(s->codec_id){
case CODEC_ID_MPEG4:
if (CONFIG_MPEG4_ENCODER)
ff_clean_mpeg4_qscales(s);
break;
case CODEC_ID_H263:
case CODEC_ID_H263P:
case CODEC_ID_FLV1:
if (CONFIG_H263_ENCODER||CONFIG_H263P_ENCODER||CONFIG_FLV_ENCODER)
ff_clean_h263_qscales(s);
break;
}
s->lambda= s->lambda_table[0];
}else
s->lambda= s->current_picture.quality;
update_qscale(s);
return 0;
}
| 1threat
|
Java Swing - how to add editable JEditorPane with scroll or movable inside : I am going to make a big box and the box uses to put many words inside.Kinda like a description box and editable.
| 0debug
|
A single column with many values separated by semicolon, R : <p>I have a column with 1000 rows. Each row has 5000 values all separated with semicolon. I like to turn this column into a matrix of 1000 x 5000 dimension.
How can I do this in R?</p>
<p>Thanks,
Aaron</p>
| 0debug
|
I want this function to loop through both lists and return the object that is the same in both. : These are the lists; note how the second list is made up of objects that need splitting first.
gaps = ['__1__', '__2__', '__3__']
questions = ['Bruce Wayne is __1__', 'Clark Kent is __2__', 'Barry Allen is __3__']
Here's the code. It seems to work only for the first (zeroth) object, bud that's it - it doesn't even loop.
def is_gap(question, gap):
place = 0
while (place < 3):
question[place] = question[place].split(' ')
for index in gaps:
if index in question[place]:
return index
else:
return None
place += 1
print is_gap(questions, gaps)
Please be gentle, I am a complete beginner!
| 0debug
|
static int coroutine_fn iscsi_co_readv(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
QEMUIOVector *iov)
{
IscsiLun *iscsilun = bs->opaque;
struct IscsiTask iTask;
uint64_t lba;
uint32_t num_sectors;
if (!is_sector_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {
return -EINVAL;
}
if (bs->bl.max_transfer_length && nb_sectors > bs->bl.max_transfer_length) {
error_report("iSCSI Error: Read of %d sectors exceeds max_xfer_len "
"of %d sectors", nb_sectors, bs->bl.max_transfer_length);
return -EINVAL;
}
if (iscsilun->lbprz && nb_sectors >= ISCSI_CHECKALLOC_THRES &&
!iscsi_allocationmap_is_allocated(iscsilun, sector_num, nb_sectors)) {
int64_t ret;
int pnum;
BlockDriverState *file;
ret = iscsi_co_get_block_status(bs, sector_num, INT_MAX, &pnum, &file);
if (ret < 0) {
return ret;
}
if (ret & BDRV_BLOCK_ZERO && pnum >= nb_sectors) {
qemu_iovec_memset(iov, 0, 0x00, iov->size);
return 0;
}
}
lba = sector_qemu2lun(sector_num, iscsilun);
num_sectors = sector_qemu2lun(nb_sectors, iscsilun);
iscsi_co_init_iscsitask(iscsilun, &iTask);
retry:
if (iscsilun->use_16_for_rw) {
iTask.task = iscsi_read16_task(iscsilun->iscsi, iscsilun->lun, lba,
num_sectors * iscsilun->block_size,
iscsilun->block_size, 0, 0, 0, 0, 0,
iscsi_co_generic_cb, &iTask);
} else {
iTask.task = iscsi_read10_task(iscsilun->iscsi, iscsilun->lun, lba,
num_sectors * iscsilun->block_size,
iscsilun->block_size,
0, 0, 0, 0, 0,
iscsi_co_generic_cb, &iTask);
}
if (iTask.task == NULL) {
return -ENOMEM;
}
scsi_task_set_iov_in(iTask.task, (struct scsi_iovec *) iov->iov, iov->niov);
while (!iTask.complete) {
iscsi_set_events(iscsilun);
qemu_coroutine_yield();
}
if (iTask.task != NULL) {
scsi_free_scsi_task(iTask.task);
iTask.task = NULL;
}
if (iTask.do_retry) {
iTask.complete = 0;
goto retry;
}
if (iTask.status != SCSI_STATUS_GOOD) {
return iTask.err_code;
}
return 0;
}
| 1threat
|
static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
{
VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);
VirtIODevice *vdev = vq->vdev;
hwaddr pa = offsetof(VRingUsed, flags);
uint16_t flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);
virtio_stw_phys_cached(vdev, &caches->used, pa, flags & ~mask);
address_space_cache_invalidate(&caches->used, pa, sizeof(flags));
}
| 1threat
|
How to parse this string? I have like a categories, can't parse it : I heve a string with links. How can i use the correct regular expression to parce it?
<li><a href="/plitka/">Керамическая плитка</a></li>
<li><a href="/napolnye-pokrytiya/">Напольные покрытия</a></li>
<li><a href="/oboi/">Обои</a></li>
<li><a href="/mebel-dlia-vannoi/">Мебель для ванной</a></li>
<li><a href="/santehnika/">Сантехника</a></li>...
Thank you very much. Really appreciate your help!
| 0debug
|
I am trying to create a string in a input box and then display the string with dashes in the lblbox for a hangman game for a class : so here is the code. These are my tasks that I am struggling with. Keep in my mind I am very new to programming. I am struggling a lot with this class and just am trying to get by with any passing grade.
-edit the program to allow a Secret Word of any length.
-the program will allow the ‘guesser’ to guess 2 times the length of the word. As an example the word ‘code’ will allow 8 total guesses.
-As the user guesses at letters contained in the word the program will:
Count the number of attempts the user has completed.
Replace the appropriate dash (-) with the correct letter, if the correct letter has been guessed.
-When all the letters have been guessed correctly all the dashes (-) should be replaced with the appropriate letters, and a message box should appear stating “Great Job playing Hangman.!”
-If the user is unable to guess the correct word in the amount of guesses allowed; the dashes (-) should be replaced with GAME OVER! and a message box should appear stating “Sorry the correct word was________”
-2 bonus points will be awarded for displaying all incorrect letters guess in a 3rd label control.
-4 more additional bonus points will be awarded for not allowing, or counting a user who guesses the same incorrect letter twice.
--------------------------------------------------------------------
Dim strSecretWord As String
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer = 10
Dim intNumofGuesses As Integer = 0
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = ""
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a 5 letter word for user to guess:", "Please input secret word.").ToUpper
'displays five dashes for the secret word
lblSecretWord.Text = lblSecretWord.Text & "-----"
'guessing player recieves inputbox to make letter guesses
MessageBox.Show("The length of the word is 5 letters, you will be given 10 guesses", "10 guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets (10) and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For intNumberofGuesses = 1 To 10
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To 4
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playign Hangman!", "Game Over", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
Else
End If
lblNumberOfAttempts.Text = intNumberofGuesses
intNumberOfRemainingGuesses = intNumberOfRemainingGuesses - 1
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
| 0debug
|
iOS Error Code=-1003 "A server with the specified hostname could not be found." : <p>I am trying to load image from URL on the iphone, image is there and I can open it in safari with same link, but not in the app:</p>
<pre><code>Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname
could not be found." UserInfo={NSUnderlyingError=0x17024f810
{Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)"
UserInfo={_kCFStreamErrorCodeKey=50331647, _kCFStreamErrorDomainKey=6147928288}},
NSErrorFailingURLStringKey=https://........, NSErrorFailingURLKey=https://.........
</code></pre>
<p>Code of request:</p>
<pre><code>func downloadImage(userEmail: String, onCompletion: @escaping (UIImage) -> Void) {
print("Download Started")
let route = "\(baseURL as String)\(userEmail as String)\(baseURLparameters as String)"
let url = URL(string: route)
getDataFromUrl(url: url!) { (data, response, error) in
guard let data = data, error == nil else {
print("===failed:", error ?? "dunno")
print("===url:", url?.absoluteString ?? "dunno")
return
}
print(response?.suggestedFilename ?? url!.lastPathComponent )
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
onCompletion(UIImage(data: data)!)
}
}
}
</code></pre>
| 0debug
|
How to properly Include Html file in Html using Html only? : I have bootstrap template called [**Couponia**][1].
I wanted to make it less coded so i choose the **embed** method to embed the Html from Another Html file.
I was try the [Javascript method][2] but without success. The PHP inclode method is irralevant.
Also [another Html method][3] didnt work at all.
My embed method is coded like that:
<embed type="text/html" src="header.html">
Now, i successeded to embed the header.html file into the index.html but as a result i got also a wierd long padding gap from the top header.
I embed this:
<div class="top-main-area text-center">
<div class="container">
<a href="index.html" class="logo mt5">
<img src="img/logos/logo4.png" />
</a>
</div>
</div>
<header class="main">
<div class="container">
<div class="row">
<div class="col-md-6">
<!-- MAIN NAVIGATION -->
<div class="flexnav-menu-button" id="flexnav-menu-button">Menu</div>
<nav>
<ul class="nav nav-pills flexnav" id="flexnav" data-breakpoint="800">
<li><a href="contact.html">Contact</a>
<ul>
</ul>
</li>
<li><a href="#">News</a>
<ul>
</ul>
</li>
<li class="active"><a href="index.html">Home</a>
<ul>
</ul>
</li>
</ul>
</nav>
<!-- END MAIN NAVIGATION -->
</div>
<div class="col-md-6">
</div>
</div>
</div>
</header>
<div class="gap"></div>
from a file **header.html** i made.
Here is how i embed it in the index.html:
<!DOCTYPE HTML>
<html>
<head>
<!-- Bootstrap styles -->
<link rel="stylesheet" href="css/boostrap.css">
<link rel="stylesheet" href="css/font_awesome.css">
<link rel="stylesheet" href="css/styles.css">
<!-- IE 8 Fallback -->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie.css" />
<![endif]-->
</head>
<body class="boxed bg-cover" style="background-image: url(img/backgrounds/wood.jpg)">
<div class="global-wrap">
<embed type="text/html" src="header.html">
I tried to play with the CSS settings but i didnt success.
Why i keep getting that long padding gap?
[1]: http://remtsoy.com/tf_templates/couponia/demo_v3_3/index-coupon-layout-2.html
[2]: http://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file
[3]: http://www.w3schools.com/howto/howto_html_include.asp
| 0debug
|
static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,
const char *name, FsCred *credp)
{
char *path;
int err = -1;
int serrno = 0;
V9fsString fullname;
char *buffer = NULL;
v9fs_string_init(&fullname);
v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);
path = fullname.data;
if (fs_ctx->export_flags & V9FS_SM_MAPPED) {
buffer = rpath(fs_ctx, path);
err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS);
if (err == -1) {
goto out;
}
credp->fc_mode = credp->fc_mode|S_IFDIR;
err = local_set_xattr(buffer, credp);
if (err == -1) {
serrno = errno;
goto err_end;
}
} else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {
buffer = rpath(fs_ctx, path);
err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS);
if (err == -1) {
goto out;
}
credp->fc_mode = credp->fc_mode|S_IFDIR;
err = local_set_mapped_file_attr(fs_ctx, path, credp);
if (err == -1) {
serrno = errno;
goto err_end;
}
} else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||
(fs_ctx->export_flags & V9FS_SM_NONE)) {
buffer = rpath(fs_ctx, path);
err = mkdir(buffer, credp->fc_mode);
if (err == -1) {
goto out;
}
err = local_post_create_passthrough(fs_ctx, path, credp);
if (err == -1) {
serrno = errno;
goto err_end;
}
}
goto out;
err_end:
remove(buffer);
errno = serrno;
out:
g_free(buffer);
v9fs_string_free(&fullname);
return err;
}
| 1threat
|
static int xenstore_scan(const char *type, int dom, struct XenDevOps *ops)
{
struct XenDevice *xendev;
char path[XEN_BUFSIZE], token[XEN_BUFSIZE];
char **dev = NULL, *dom0;
unsigned int cdev, j;
dom0 = xs_get_domain_path(xenstore, 0);
snprintf(token, sizeof(token), "be:%p:%d:%p", type, dom, ops);
snprintf(path, sizeof(path), "%s/backend/%s/%d", dom0, type, dom);
free(dom0);
if (!xs_watch(xenstore, path, token)) {
xen_be_printf(NULL, 0, "xen be: watching backend path (%s) failed\n", path);
return -1;
}
dev = xs_directory(xenstore, 0, path, &cdev);
if (!dev) {
return 0;
}
for (j = 0; j < cdev; j++) {
xendev = xen_be_get_xendev(type, dom, atoi(dev[j]), ops);
if (xendev == NULL) {
continue;
}
xen_be_check_state(xendev);
}
free(dev);
return 0;
}
| 1threat
|
Android Emulator Seems to Record Audio at 96khz : <p>My app is recording audio from phone's microphones and does some real time processing on it. It's working fine on physical devices, but acts "funny" in emulator. It records something, but I'm not quite sure what it is it's recording. </p>
<p><strong>It appears that on emulator the audio samples are being read at about double the rate as on actual devices.</strong> In the app I have a visual progress widget (a horizontally moving recording head), which moves about twice as fast in emulator. </p>
<p>Here is the recording loop:</p>
<pre><code>int FREQUENCY = 44100;
int BLOCKSIZE = 110;
int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT) * 10;
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER,
FREQUENCY, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
short[] signal = new short[BLOCKSIZE * 2]; // Times two for stereo
audioRecord.startRecording();
while (!isCancelled()) {
int bufferReadResult = audioRecord.read(signal, 0, BLOCKSIZE * 2);
if (bufferReadResult != BLOCKSIZE * 2)
throw new RuntimeException("Recorded less than BLOCKSIZE x 2 samples:"
+ bufferReadResult);
// process the `signal` array here
}
audioRecord.stop();
audioRecord.release();
</code></pre>
<p>The audio source is set to "CAMCORDER" and it records in stereo. The idea is, if the phone has multiple microphones, the app will process data from both and use whichever has better SNR. But I have the same problems if recording mono from <code>AudioSource.MIC</code>. It reads audio data in a <code>while</code> loop, I am assuming that <code>audioRecord.read()</code> is a blocking call and will not let me read same data twice.</p>
<p>The recorded data looks OK – the record buffer contains 16-bit PCM samples for two channels. The loop just seems to be running at twice the speed as on real devices. Which leads me to think that maybe the emulator is using a higher sampling rate than the specified 44100Hz. If I query the sample rate with <code>audioRecord.getSampleRate()</code> it returns the correct value. </p>
<p>Also there are some interesting audio related messages in logcat while recording:</p>
<pre><code>07-13 12:22:02.282 1187 1531 D AudioFlinger: mixer(0xf44c0000) throttle end: throttle time(154)
(...)
07-13 12:22:02.373 1187 1817 E audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
07-13 12:22:02.373 1187 3036 I AudioFlinger: AudioFlinger's thread 0xf3bc0000 ready to run
07-13 12:22:02.403 1187 3036 W AudioFlinger: RecordThread: buffer overflow
(...)
07-13 12:22:24.792 1187 3036 W AudioFlinger: RecordThread: buffer overflow
07-13 12:22:30.677 1187 3036 W AudioFlinger: RecordThread: buffer overflow
07-13 12:22:37.722 1187 3036 W AudioFlinger: RecordThread: buffer overflow
</code></pre>
<p>I'm using up-to-date Android Studio and Android SDK, and I have tried emulator images running API levels 21-24. My dev environment is Ubuntu 16.04</p>
<p>Has anybody experienced something similar?
Am I doing something wrong in my recording loop? </p>
| 0debug
|
How would I create a python function that outputs all combinations of a defined set of variables? : <p>Here is what I am trying to do but not exactly sure how to make this work. I have 3 sets of variables and I want to output all combinations of those 3 sets and output in a format that maintains the order of the variables like this:</p>
<pre><code>list_of_vars = [var1, var2, var3]
</code></pre>
<p>The variables would look something like this:</p>
<pre><code>var1 = [1, 2, 3]
var2 = ["foo", "bar", "foo2"]
var3 = ["a", "b", "c"]
</code></pre>
<p>The final output should look like this.</p>
<pre><code>final_list_of_vars = [[1, "foo", a], [1, "bar", a], .......]
</code></pre>
| 0debug
|
Computer vision (Alignment using opencv c++) : [Hello everyone
I am trying to use getPerspectiveTransform or getAffineTransform function in Visual Studio but when I run the code this message appears to me and the code don't work well at all.
This is a part of my code
"
//Mat im_src = imread("img_name.png",-1);
// Five corners of the source image
vector<Point2f> pts_src;
pts_src.push_back(Point2f(106, 115));
pts_src.push_back(Point2f(141, 111));
pts_src.push_back(Point2f(129, 134));
pts_src.push_back(Point2f(109, 150));
pts_src.push_back(Point2f(147, 146));
// Read destination
// Five corners of the book in destination image.
vector<Point2f> pts_dst;
pts_dst.push_back(Point2f(30.2946, 51.6963));
pts_dst.push_back(Point2f(65.5318, 51.5014));
pts_dst.push_back(Point2f(48.0252, 71.7366));
pts_dst.push_back(Point2f(33.5493, 92.3655));
pts_dst.push_back(Point2f(62.7299, 92.2041));
// Calculate Homography
Mat h = cv::getPerspectiveTransform(pts_src, pts_dst);
//The error is due to the previous line
// Output image
Mat im_out;
// Warp source image to destination based on homography
Size imgSize(112, 96);
warpPerspective(img, im_out, h, imgSize);
// Display images
imshow("Source Image", im_src);
imshow("Warped Source Image", im_out);
"
Please can anyone help me ][1]
[1]: https://i.stack.imgur.com/7kbLA.png
| 0debug
|
static void virtio_gpu_handle_cursor(VirtIODevice *vdev, VirtQueue *vq)
{
VirtIOGPU *g = VIRTIO_GPU(vdev);
VirtQueueElement elem;
size_t s;
struct virtio_gpu_update_cursor cursor_info;
if (!virtio_queue_ready(vq)) {
return;
}
while (virtqueue_pop(vq, &elem)) {
s = iov_to_buf(elem.out_sg, elem.out_num, 0,
&cursor_info, sizeof(cursor_info));
if (s != sizeof(cursor_info)) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: cursor size incorrect %zu vs %zu\n",
__func__, s, sizeof(cursor_info));
} else {
update_cursor(g, &cursor_info);
}
virtqueue_push(vq, &elem, 0);
virtio_notify(vdev, vq);
}
}
| 1threat
|
javascript import from '/folder' with index.js : <p>I've noticed a few cases where I've seen something like the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// /reducers/reducer1.js
export default function reducer1(state = {}, action){
// etc...
}
// /reducers/reducer2.js
export default function reducer2(state = {}, action){
// etc...
}
// /reducers/index.js
import { combineReducers } from 'redux';
import reducer1 from './reducer1';
import reducer2 from './reducer2';
export default combineReducers({
reducer1,
reducer2
})
// /store.js
import masterReducer from './reducers';
export default function makeStore(){
// etc...
}</code></pre>
</div>
</div>
</p>
<p>Notice the last "file" where we call <code>import masterReducer from './reducers'</code> - A few people seem to believe this should import the <code>default export</code> from the index.js file.</p>
<p>Is this actually part of the specification? - my interpretation/question is that this is the result of many folks using WebPack v1 which translates <code>import</code> statements into CommonJS-style <code>requires</code> statements? Or will this break in WebPack v2 with "official" <code>import</code>/<code>export</code> support?</p>
| 0debug
|
bool hvf_inject_interrupts(CPUState *cpu_state)
{
int allow_nmi = !(rvmcs(cpu_state->hvf_fd, VMCS_GUEST_INTERRUPTIBILITY) &
VMCS_INTERRUPTIBILITY_NMI_BLOCKING);
X86CPU *x86cpu = X86_CPU(cpu_state);
CPUX86State *env = &x86cpu->env;
uint64_t idt_info = rvmcs(cpu_state->hvf_fd, VMCS_IDT_VECTORING_INFO);
uint64_t info = 0;
if (idt_info & VMCS_IDT_VEC_VALID) {
uint8_t vector = idt_info & 0xff;
uint64_t intr_type = idt_info & VMCS_INTR_T_MASK;
info = idt_info;
uint64_t reason = rvmcs(cpu_state->hvf_fd, VMCS_EXIT_REASON);
if (intr_type == VMCS_INTR_T_NMI && reason != EXIT_REASON_TASK_SWITCH) {
allow_nmi = 1;
vmx_clear_nmi_blocking(cpu_state);
}
if ((allow_nmi || intr_type != VMCS_INTR_T_NMI)) {
info &= ~(1 << 12);
if (intr_type == VMCS_INTR_T_SWINTR ||
intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
intr_type == VMCS_INTR_T_SWEXCEPTION) {
uint64_t ins_len = rvmcs(cpu_state->hvf_fd,
VMCS_EXIT_INSTRUCTION_LENGTH);
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_INST_LENGTH, ins_len);
}
if (vector == EXCEPTION_BP || vector == EXCEPTION_OF) {
info &= ~VMCS_INTR_T_MASK;
info |= VMCS_INTR_T_SWEXCEPTION;
uint64_t ins_len = rvmcs(cpu_state->hvf_fd,
VMCS_EXIT_INSTRUCTION_LENGTH);
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_INST_LENGTH, ins_len);
}
uint64_t err = 0;
if (idt_info & VMCS_INTR_DEL_ERRCODE) {
err = rvmcs(cpu_state->hvf_fd, VMCS_IDT_VECTORING_ERROR);
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_EXCEPTION_ERROR, err);
}
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_INTR_INFO, info);
};
}
if (cpu_state->interrupt_request & CPU_INTERRUPT_NMI) {
if (allow_nmi && !(info & VMCS_INTR_VALID)) {
cpu_state->interrupt_request &= ~CPU_INTERRUPT_NMI;
info = VMCS_INTR_VALID | VMCS_INTR_T_NMI | NMI_VEC;
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_INTR_INFO, info);
} else {
vmx_set_nmi_window_exiting(cpu_state);
}
}
if (env->hvf_emul->interruptable &&
(cpu_state->interrupt_request & CPU_INTERRUPT_HARD) &&
(EFLAGS(env) & IF_MASK) && !(info & VMCS_INTR_VALID)) {
int line = cpu_get_pic_interrupt(&x86cpu->env);
cpu_state->interrupt_request &= ~CPU_INTERRUPT_HARD;
if (line >= 0) {
wvmcs(cpu_state->hvf_fd, VMCS_ENTRY_INTR_INFO, line |
VMCS_INTR_VALID | VMCS_INTR_T_HWINTR);
}
}
if (cpu_state->interrupt_request & CPU_INTERRUPT_HARD) {
vmx_set_int_window_exiting(cpu_state);
}
}
| 1threat
|
FsTypeEntry *get_fsdev_fsentry(char *id)
{
struct FsTypeListEntry *fsle;
QTAILQ_FOREACH(fsle, &fstype_entries, next) {
if (strcmp(fsle->fse.fsdev_id, id) == 0) {
return &fsle->fse;
}
}
return NULL;
}
| 1threat
|
Change coding in java script function : <p>I have never seen it, but is there a way to modify the existing java script function through the code? Something similar to "ALTER PROCEDURE..." statement in SQL Server? </p>
<p>Thank you!</p>
| 0debug
|
Unexpected side effect with java streams reduce operation : <p>I'm observing a side effect on an underlying collection when calling 'reduce' on a Stream. This is so basic. I can't believe what I am seeing, but I can't find the error. Below is the code and the resulting output. Can anyone explain to me why one of the underlying collections of the Stream is mutating?</p>
<pre><code>package top;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
ArrayList<Integer> list3 = new ArrayList<>();
list1.addAll(Arrays.asList(1, 2, 3));
list2.addAll(Arrays.asList(4, 5, 6));
list3.addAll(Arrays.asList(7, 8, 9));
System.out.println("Before");
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
ArrayList<Integer> r1 = Stream.of(list1, list2, list3).reduce((l, r) -> {
l.addAll(r);
return l;
}).orElse(new ArrayList<>());
System.out.println("After");
System.out.println(list1);
System.out.println(list2);
System.out.println(list3);
System.out.println("Result");
System.out.println(r1);
}
}
// Output
Before
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
After
[1, 2, 3, 4, 5, 6, 7, 8, 9] // Why is this not [1,2,3]?
[4, 5, 6]
[7, 8, 9]
Result
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 0debug
|
import re
def remove_uppercase(str1):
remove_upper = lambda text: re.sub('[A-Z]', '', text)
result = remove_upper(str1)
return (result)
| 0debug
|
why array is not obsolete after collection comes in java : <p>In java post collection , we can do all thing which we could do by array and some other stuffs using collection . so my question is can array be obsolete in future ? </p>
| 0debug
|
pandas - Merging on string columns not working (bug?) : <p>I'm trying to do a simple merge between two dataframes. These come from two different SQL tables, where the joining keys are strings:</p>
<pre><code>>>> df1.col1.dtype
dtype('O')
>>> df2.col2.dtype
dtype('O')
</code></pre>
<p>I try to merge them using this:</p>
<pre><code>>>> merge_res = pd.merge(df1, df2, left_on='col1', right_on='col2')
</code></pre>
<p>The result of the inner join is empty, which first prompted me that there might not be any entries in the intersection:</p>
<pre><code>>>> merge_res.shape
(0, 19)
</code></pre>
<p>But when I try to match a single element, I see this really odd behavior.</p>
<pre><code># Pick random element in second dataframe
>>> df2.iloc[5,:].col2
'95498208100000'
# Manually look for it in the first dataframe
>>> df1[df1.col1 == '95498208100000']
0 rows × 19 columns
# Empty, which makes sense given the above merge result
# Now look for the same value as an integer
>>> df1[df1.col1 == 95498208100000]
1 rows × 19 columns
# FINDS THE ELEMENT!?!
</code></pre>
<p>So, the columns are defined with the 'object' dtype. Searching for them as strings don't yield any results. Searching for them as integers does return a result, and I think this is the reason why the merge doesn't work above..</p>
<p>Any ideas what's going on?</p>
<p>It's almost as thought Pandas converts <code>df1.col1</code> to an integer just because it can, even though it <em>should</em> be treated as a string while matching. </p>
<p>(I tried to replicate this using sample dataframes, but for small examples, I don't see this behavior. Any suggestions on how I can find a more descriptive example would be appreciated as well.)</p>
| 0debug
|
static void create_cpu_without_cps(const char *cpu_model,
qemu_irq *cbus_irq, qemu_irq *i8259_irq)
{
CPUMIPSState *env;
MIPSCPU *cpu;
int i;
for (i = 0; i < smp_cpus; i++) {
cpu = cpu_mips_init(cpu_model);
if (cpu == NULL) {
fprintf(stderr, "Unable to find CPU definition\n");
exit(1);
}
cpu_mips_irq_init_cpu(cpu);
cpu_mips_clock_init(cpu);
qemu_register_reset(main_cpu_reset, cpu);
}
cpu = MIPS_CPU(first_cpu);
env = &cpu->env;
*i8259_irq = env->irq[2];
*cbus_irq = env->irq[4];
}
| 1threat
|
How to compute all second derivatives (only the diagonal of the Hessian matrix) in Tensorflow? : <p>I have a <strong>loss</strong> value/function and I would like to compute all the second derivatives with respect to a tensor <strong>f</strong> (of size n). I managed to use tf.gradients twice, but when applying it for the second time, it sums the derivatives across the first input (see <em>second_derivatives</em> in my code). </p>
<p>Also I managed to retrieve the Hessian matrix, but I would like to only compute its diagonal to avoid extra-computation.</p>
<pre><code>import tensorflow as tf
import numpy as np
f = tf.Variable(np.array([[1., 2., 0]]).T)
loss = tf.reduce_prod(f ** 2 - 3 * f + 1)
first_derivatives = tf.gradients(loss, f)[0]
second_derivatives = tf.gradients(first_derivatives, f)[0]
hessian = [tf.gradients(first_derivatives[i,0], f)[0][:,0] for i in range(3)]
model = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(model)
print "\nloss\n", sess.run(loss)
print "\nloss'\n", sess.run(first_derivatives)
print "\nloss''\n", sess.run(second_derivatives)
hessian_value = np.array(map(list, sess.run(hessian)))
print "\nHessian\n", hessian_value
</code></pre>
<p>My thinking was that <strong>tf.gradients(first_derivatives, f[0, 0])[0]</strong> would work to retrieve for instance the second derivative with respect to f_0 but it seems that tensorflow doesn't allow to derive from a slice of a tensor.</p>
| 0debug
|
how can order by last replies? : I am new in php
I have two tables the first is the 'users' the second is the 'posts',
the 'users' have two columns:
1 id
2 username
the 'posts' have five columns:
1 p_id
2 uid
3 post_id
4 content
5 date
the posts as defined have the value '0' in post_id and the replies have the value p_id in post_id
my query is `SELECT id,username,p_id,uid,post_id,content,date FROM
users inner join posts ON users.id=posts.uid WHERE post_id='0' ORDER BY p_id DESC`
but I want to order by the last replies like in the forums .
I am wating for your help thank you
| 0debug
|
Rails 5.2.0 with Ruby 2.5.1 console - `warning:` `already` initialized constant FileUtils::VERSION : <p>I'm currently experiencing an issue with my new rails application, more specifically:</p>
<ul>
<li>Rails 5.2.0</li>
<li>Ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]</li>
<li>rvm 1.29.4 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [<a href="https://rvm.io]" rel="noreferrer">https://rvm.io]</a></li>
</ul>
<p>When I run <code>rails c</code>, it produces a warning links to fileutils gem as the following:</p>
<pre><code>`/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:90:` `warning:` `already` initialized constant FileUtils::VERSION
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:92: warning: previous definition of VERSION was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1188: warning: already initialized constant FileUtils::Entry_::S_IF_DOOR
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1267: warning: previous definition of S_IF_DOOR was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1446: warning: already initialized constant FileUtils::Entry_::DIRECTORY_TERM
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1541: warning: previous definition of DIRECTORY_TERM was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1448: warning: already initialized constant FileUtils::Entry_::SYSCASE
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1543: warning: previous definition of SYSCASE was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1501: warning: already initialized constant FileUtils::OPT_TABLE
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1596: warning: previous definition of OPT_TABLE was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1555: warning: already initialized constant FileUtils::LOW_METHODS
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1650: warning: previous definition of LOW_METHODS was here
/usr/local/Cellar/ruby/2.5.1/lib/ruby/2.5.0/fileutils.rb:1562: warning: already initialized constant FileUtils::METHODS
/usr/local/lib/ruby/gems/2.5.0/gems/fileutils-1.1.0/lib/fileutils.rb:1657: warning: previous definition of METHODS was here
</code></pre>
<p>I follow all the step as outlined in this guideline <code>http://railsapps.github.io/installrubyonrails-mac.html</code>.</p>
<p>You can replicate the issue by just following the guideline or with the following steps:</p>
<ol>
<li>rvm install ruby-2.5.1</li>
<li>rails new app</li>
<li>cd app</li>
<li>gem update</li>
<li>bundle update</li>
</ol>
<p>After observing and working around, I've found that the default version of fileutils come with Ruby 2.5.* is 1.0.2 and the <code>gem update</code> command installs a another newer version 1.1.0. Therefore, there are two versions of <code>fileutils</code> are loaded when I run the <code>rails c</code>. </p>
<p>To deal with this issue, I append <code>--default</code> option to the <code>gem update</code> command. </p>
<pre><code>gem update --default
</code></pre>
<p>As a result, I got two default versions which can be seen by running <code>gem list | grep fileutils</code>. This is the only way I can get rid the warning.</p>
<pre><code>mac: gem list | grep fileutils
fileutils (default: 1.1.0, default: 1.0.2)
</code></pre>
<p>I write this question with, kind of, answer just to share with someone who may experience the same issue. I spent hours to sort it out as I couldn't find any helps on the internet.</p>
<p><strong><em>Note</em></strong>: the same issue happens when I use <code>rbenv</code> instead of <code>rvm</code> on macOS Sierra.</p>
<p>Please let me know if anyone has a better approach to deal with such an issue.</p>
<p>Cheers,</p>
| 0debug
|
static void test_qemu_strtosz_trailing(void)
{
const char *str;
char *endptr = NULL;
int64_t res;
str = "123xxx";
res = qemu_strtosz_MiB(str, &endptr);
g_assert_cmpint(res, ==, 123 * M_BYTE);
g_assert(endptr == str + 3);
res = qemu_strtosz(str, NULL);
g_assert_cmpint(res, ==, -EINVAL);
str = "1kiB";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 1024);
g_assert(endptr == str + 2);
res = qemu_strtosz(str, NULL);
g_assert_cmpint(res, ==, -EINVAL);
}
| 1threat
|
What does html mean : <p>what does it mean s <em>this</em>.</p>
<p><strong>This is bold</strong>, just like <strong>this</strong>.</p>
<p>You can <strong><em>combine</em></strong> them
if you <strong><em>really have to</em></strong>.</p>
| 0debug
|
ip_reass(register struct ip *ip, register struct ipq *fp)
{
register struct mbuf *m = dtom(ip);
register struct ipasfrag *q;
int hlen = ip->ip_hl << 2;
int i, next;
DEBUG_CALL("ip_reass");
DEBUG_ARG("ip = %lx", (long)ip);
DEBUG_ARG("fp = %lx", (long)fp);
DEBUG_ARG("m = %lx", (long)m);
m->m_data += hlen;
m->m_len -= hlen;
if (fp == 0) {
struct mbuf *t;
if ((t = m_get()) == NULL) goto dropfrag;
fp = mtod(t, struct ipq *);
insque(&fp->ip_link, &ipq.ip_link);
fp->ipq_ttl = IPFRAGTTL;
fp->ipq_p = ip->ip_p;
fp->ipq_id = ip->ip_id;
fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;
fp->ipq_src = ip->ip_src;
fp->ipq_dst = ip->ip_dst;
q = (struct ipasfrag *)fp;
goto insert;
}
for (q = fp->frag_link.next; q != (struct ipasfrag *)&fp->frag_link;
q = q->ipf_next)
if (q->ipf_off > ip->ip_off)
break;
if (q->ipf_prev != &fp->frag_link) {
struct ipasfrag *pq = q->ipf_prev;
i = pq->ipf_off + pq->ipf_len - ip->ip_off;
if (i > 0) {
if (i >= ip->ip_len)
goto dropfrag;
m_adj(dtom(ip), i);
ip->ip_off += i;
ip->ip_len -= i;
}
}
while (q != (struct ipasfrag*)&fp->frag_link &&
ip->ip_off + ip->ip_len > q->ipf_off) {
i = (ip->ip_off + ip->ip_len) - q->ipf_off;
if (i < q->ipf_len) {
q->ipf_len -= i;
q->ipf_off += i;
m_adj(dtom(q), i);
break;
}
q = q->ipf_next;
m_freem(dtom(q->ipf_prev));
ip_deq(q->ipf_prev);
}
insert:
ip_enq(iptofrag(ip), q->ipf_prev);
next = 0;
for (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;
q = q->ipf_next) {
if (q->ipf_off != next)
return (0);
next += q->ipf_len;
}
if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)
return (0);
q = fp->frag_link.next;
m = dtom(q);
q = (struct ipasfrag *) q->ipf_next;
while (q != (struct ipasfrag*)&fp->frag_link) {
struct mbuf *t = dtom(q);
q = (struct ipasfrag *) q->ipf_next;
m_cat(m, t);
}
q = fp->frag_link.next;
if (m->m_flags & M_EXT) {
int delta;
delta = (char *)ip - m->m_dat;
q = (struct ipasfrag *)(m->m_ext + delta);
}
ip = fragtoip(q);
ip->ip_len = next;
ip->ip_tos &= ~1;
ip->ip_src = fp->ipq_src;
ip->ip_dst = fp->ipq_dst;
remque(&fp->ip_link);
(void) m_free(dtom(fp));
m->m_len += (ip->ip_hl << 2);
m->m_data -= (ip->ip_hl << 2);
return ip;
dropfrag:
STAT(ipstat.ips_fragdropped++);
m_freem(m);
return (0);
}
| 1threat
|
Android ViewModel call Activity methods : <p>I'm using android AAC library and Android databinding library in my project. I have AuthActivity and AuthViewModel extends android's ViewModel class. In some cases i need to ask for Activity to call some methods for ViewModel.
For example when user click on Google Auth or Facebook Auth button, which initialized in Activity class (because to initialize GoogleApiClient i need Activity context which i can not pass to ViewModel, view model can not store Activity fields).
All logic with Google Api and Facebook API implemented in Activity class:</p>
<pre><code>//google api initialization
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//facebook login button
loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
loginButton.registerCallback(callbackManager,
</code></pre>
<p>Also i need to call sign in intent which requires Activity context too:</p>
<pre><code>Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(signInIntent, GOOGLE_AUTH);
</code></pre>
<p>I can not request facebook login and google login, or startActivity intent from view model class, so i created class interface AuthActivityListener:</p>
<pre><code>public interface AuthActivityListener {
void requestSignedIn();
void requestGoogleAuth();
void requestFacebookAuth();
void requestShowDialogFragment(int type);
}
</code></pre>
<p>Implement listener in activity class:</p>
<pre><code>AuthActivityRequester authRequestListener = new AuthActivityRequester() {
@Override
public void requestSignedIn() {
Intent intent = new Intent(AuthActivity.this, ScanActivity.class);
startActivity(intent);
AuthActivity.this.finish();
}
@Override
public void requestGoogleAuth() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(signInIntent, GOOGLE_AUTH);
}
...
</code></pre>
<p>And assign this listener in view model class to call activity methods:</p>
<pre><code>// in constructor
this.authRequester = listener;
// call activity method
public void onClickedAuthGoogle() {
authRequester.requestGoogleAuth();
}
</code></pre>
<p>After google or facebook authentication passed i call view model method from activity:</p>
<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOOGLE_AUTH) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
if (acct != null) {
viewModel.onGoogleUserLoaded(acct.getEmail(), acct.getId());
} else {
viewModel.onGoogleUserLoaded("", "");
}
}
}
}
</code></pre>
<p>Can anyone explain me is this approach of communication between view model and activity is right, or i need to find another way to call activity methods from view model ?</p>
| 0debug
|
Thread vs CompletableFuture : <p>What is the advantage of passing code directly to thread vs using CompletableFuture instead?</p>
<pre><code>Thread thread = new Thread(() -> {do something});
thread.start();
</code></pre>
<p>VS</p>
<pre><code>CompletableFuture<Void> cf1 =
CompletableFuture.runAsync(() -> {do something});
</code></pre>
| 0debug
|
static int avi_read_idx1(AVFormatContext *s, int size)
{
AVIContext *avi = s->priv_data;
AVIOContext *pb = s->pb;
int nb_index_entries, i;
AVStream *st;
AVIStream *ast;
unsigned int index, tag, flags, pos, len, first_packet = 1;
unsigned last_pos= -1;
int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
nb_index_entries = size / 16;
if (nb_index_entries <= 0)
return -1;
idx1_pos = avio_tell(pb);
avio_seek(pb, avi->movi_list+4, SEEK_SET);
if (avi_sync(s, 1) == 0) {
first_packet_pos = avio_tell(pb) - 8;
}
avi->stream_index = -1;
avio_seek(pb, idx1_pos, SEEK_SET);
for(i = 0; i < nb_index_entries; i++) {
tag = avio_rl32(pb);
flags = avio_rl32(pb);
pos = avio_rl32(pb);
len = avio_rl32(pb);
av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
i, tag, flags, pos, len);
index = ((tag & 0xff) - '0') * 10;
index += ((tag >> 8) & 0xff) - '0';
if (index >= s->nb_streams)
continue;
st = s->streams[index];
ast = st->priv_data;
if(first_packet && first_packet_pos && len) {
data_offset = first_packet_pos - pos;
first_packet = 0;
}
pos += data_offset;
av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
if(pb->eof_reached)
return -1;
if(last_pos == pos)
avi->non_interleaved= 1;
else if(len || !ast->sample_size)
av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
ast->cum_len += get_duration(ast, len);
last_pos= pos;
}
return 0;
}
| 1threat
|
how to get numbers from a string and add them : I want the program to find number from a string and return the value. In case a string contains more than one number then it should add all the numbers in string and return the value.
For Ex: "20 min was spent on team huddle meeting and 90 minutes were spend on training"
So the return value should be 110 (90+20)
| 0debug
|
How to make keypress (keydown) close program in VB.NET : I'm currently writing code for a project in VB.NET where if you hit the "escape" button you get a messagebox saying "This exits the program, would you like to leave? 'Y' or 'N'". What code would I write to make it so that if you hit "Y" the program closes?
This is what I have so far:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then
MsgBox("This button exits the program. Do you want to exit the program?")
If Button = e.KeyCode = Keys.Y Then
End
End If
End If
End Sub
What exactly should I add? Thanks in advance!
| 0debug
|
int ff_h263_decode_frame(AVCodecContext *avctx,
void *data, int *data_size,
uint8_t *buf, int buf_size)
{
MpegEncContext *s = avctx->priv_data;
int ret;
AVFrame *pict = data;
#ifdef PRINT_FRAME_TIME
uint64_t time= rdtsc();
#endif
#ifdef DEBUG
printf("*****frame %d size=%d\n", avctx->frame_number, buf_size);
printf("bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);
#endif
s->flags= avctx->flags;
s->flags2= avctx->flags2;
if (buf_size == 0) {
if (s->low_delay==0 && s->next_picture_ptr) {
*pict= *(AVFrame*)s->next_picture_ptr;
s->next_picture_ptr= NULL;
*data_size = sizeof(AVFrame);
}
return 0;
}
if(s->flags&CODEC_FLAG_TRUNCATED){
int next;
if(s->codec_id==CODEC_ID_MPEG4){
next= ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);
}else if(s->codec_id==CODEC_ID_H263){
next= h263_find_frame_end(&s->parse_context, buf, buf_size);
}else{
av_log(s->avctx, AV_LOG_ERROR, "this codec doesnt support truncated bitstreams\n");
return -1;
}
if( ff_combine_frame(&s->parse_context, next, &buf, &buf_size) < 0 )
return buf_size;
}
retry:
if(s->bitstream_buffer_size && (s->divx_packed || buf_size<20)){
init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size*8);
}else
init_get_bits(&s->gb, buf, buf_size*8);
s->bitstream_buffer_size=0;
if (!s->context_initialized) {
if (MPV_common_init(s) < 0)
return -1;
}
if(s->current_picture_ptr==NULL || s->current_picture_ptr->data[0]){
int i= ff_find_unused_picture(s, 0);
s->current_picture_ptr= &s->picture[i];
}
if (s->msmpeg4_version==5) {
ret= ff_wmv2_decode_picture_header(s);
} else if (s->msmpeg4_version) {
ret = msmpeg4_decode_picture_header(s);
} else if (s->h263_pred) {
if(s->avctx->extradata_size && s->picture_number==0){
GetBitContext gb;
init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);
ret = ff_mpeg4_decode_picture_header(s, &gb);
}
ret = ff_mpeg4_decode_picture_header(s, &s->gb);
if(s->flags& CODEC_FLAG_LOW_DELAY)
s->low_delay=1;
} else if (s->codec_id == CODEC_ID_H263I) {
ret = intel_h263_decode_picture_header(s);
} else if (s->h263_flv) {
ret = flv_h263_decode_picture_header(s);
} else {
ret = h263_decode_picture_header(s);
}
if(ret==FRAME_SKIPED) return get_consumed_bytes(s, buf_size);
if (ret < 0){
av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
return -1;
}
avctx->has_b_frames= !s->low_delay;
if(s->xvid_build==0 && s->divx_version==0 && s->lavc_build==0){
if(s->avctx->stream_codec_tag == ff_get_fourcc("XVID") ||
s->avctx->codec_tag == ff_get_fourcc("XVID") || s->avctx->codec_tag == ff_get_fourcc("XVIX"))
s->xvid_build= -1;
#if 0
if(s->avctx->codec_tag == ff_get_fourcc("DIVX") && s->vo_type==0 && s->vol_control_parameters==1
&& s->padding_bug_score > 0 && s->low_delay)
s->xvid_build= -1;
#endif
}
if(s->xvid_build==0 && s->divx_version==0 && s->lavc_build==0){
if(s->avctx->codec_tag == ff_get_fourcc("DIVX") && s->vo_type==0 && s->vol_control_parameters==0)
s->divx_version= 400;
}
if(s->workaround_bugs&FF_BUG_AUTODETECT){
s->workaround_bugs &= ~FF_BUG_NO_PADDING;
if(s->padding_bug_score > -2 && !s->data_partitioning && (s->divx_version || !s->resync_marker))
s->workaround_bugs |= FF_BUG_NO_PADDING;
if(s->avctx->codec_tag == ff_get_fourcc("XVIX"))
s->workaround_bugs|= FF_BUG_XVID_ILACE;
if(s->avctx->codec_tag == ff_get_fourcc("UMP4")){
s->workaround_bugs|= FF_BUG_UMP4;
}
if(s->divx_version>=500){
s->workaround_bugs|= FF_BUG_QPEL_CHROMA;
}
if(s->divx_version>502){
s->workaround_bugs|= FF_BUG_QPEL_CHROMA2;
}
if(s->xvid_build && s->xvid_build<=3)
s->padding_bug_score= 256*256*256*64;
if(s->xvid_build && s->xvid_build<=1)
s->workaround_bugs|= FF_BUG_QPEL_CHROMA;
if(s->xvid_build && s->xvid_build<=12)
s->workaround_bugs|= FF_BUG_EDGE;
if(s->xvid_build && s->xvid_build<=32)
s->workaround_bugs|= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->dsp.put_ ## postfix1 = ff_put_ ## postfix2;\
s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;\
s->dsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if(s->lavc_build && s->lavc_build<4653)
s->workaround_bugs|= FF_BUG_STD_QPEL;
if(s->lavc_build && s->lavc_build<4655)
s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;
if(s->lavc_build && s->lavc_build<4670){
s->workaround_bugs|= FF_BUG_EDGE;
}
if(s->lavc_build && s->lavc_build<=4712)
s->workaround_bugs|= FF_BUG_DC_CLIP;
if(s->divx_version)
s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;
if(s->divx_version==501 && s->divx_build==20020416)
s->padding_bug_score= 256*256*256*64;
if(s->divx_version && s->divx_version<500){
s->workaround_bugs|= FF_BUG_EDGE;
}
if(s->divx_version)
s->workaround_bugs|= FF_BUG_HPEL_CHROMA;
#if 0
if(s->divx_version==500)
s->padding_bug_score= 256*256*256*64;
if( s->resync_marker==0 && s->data_partitioning==0 && s->divx_version==0
&& s->codec_id==CODEC_ID_MPEG4 && s->vo_type==0)
s->workaround_bugs|= FF_BUG_NO_PADDING;
if(s->lavc_build && s->lavc_build<4609)
s->workaround_bugs|= FF_BUG_NO_PADDING;
#endif
}
if(s->workaround_bugs& FF_BUG_STD_QPEL){
SET_QPEL_FUNC(qpel_pixels_tab[0][ 5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][ 7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][ 9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][ 5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][ 7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][ 9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if(avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, s->lavc_build, s->xvid_build, s->divx_version, s->divx_build,
s->divx_packed ? "p" : "");
#if 0
{
static FILE *f=NULL;
if(!f) f=fopen("rate_qp_cplx.txt", "w");
fprintf(f, "%d %d %f\n", buf_size, s->qscale, buf_size*(double)s->qscale);
}
#endif
if ( s->width != avctx->width || s->height != avctx->height) {
ParseContext pc= s->parse_context;
s->parse_context.buffer=0;
MPV_common_end(s);
s->parse_context= pc;
}
if (!s->context_initialized) {
avctx->width = s->width;
avctx->height = s->height;
goto retry;
}
if((s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P))
s->gob_index = ff_h263_get_gob_height(s);
s->current_picture.pict_type= s->pict_type;
s->current_picture.key_frame= s->pict_type == I_TYPE;
if(s->last_picture_ptr==NULL && s->pict_type==B_TYPE) return get_consumed_bytes(s, buf_size);
if(avctx->hurry_up && s->pict_type==B_TYPE) return get_consumed_bytes(s, buf_size);
if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);
if(s->next_p_frame_damaged){
if(s->pict_type==B_TYPE)
return get_consumed_bytes(s, buf_size);
else
s->next_p_frame_damaged=0;
}
if(MPV_frame_start(s, avctx) < 0)
return -1;
#ifdef DEBUG
printf("qscale=%d\n", s->qscale);
#endif
ff_er_frame_start(s);
if (s->msmpeg4_version==5){
if(ff_wmv2_decode_secondary_picture_header(s) < 0)
return -1;
}
s->mb_x=0;
s->mb_y=0;
decode_slice(s);
while(s->mb_y<s->mb_height){
if(s->msmpeg4_version){
if(s->mb_x!=0 || (s->mb_y%s->slice_height)!=0 || get_bits_count(&s->gb) > s->gb.size_in_bits)
break;
}else{
if(ff_h263_resync(s)<0)
break;
}
if(s->msmpeg4_version<4 && s->h263_pred)
ff_mpeg4_clean_buffers(s);
decode_slice(s);
}
if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type==I_TYPE)
if(msmpeg4_decode_ext_header(s, buf_size) < 0){
s->error_status_table[s->mb_num-1]= AC_ERROR|DC_ERROR|MV_ERROR;
}
if(s->codec_id==CODEC_ID_MPEG4 && s->bitstream_buffer_size==0 && s->divx_packed){
int current_pos= get_bits_count(&s->gb)>>3;
int startcode_found=0;
if( buf_size - current_pos > 5
&& buf_size - current_pos < BITSTREAM_BUFFER_SIZE){
int i;
for(i=current_pos; i<buf_size-3; i++){
if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1 && buf[i+3]==0xB6){
startcode_found=1;
break;
}
}
}
if(s->gb.buffer == s->bitstream_buffer && buf_size>20){
startcode_found=1;
current_pos=0;
}
if(startcode_found){
memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos);
s->bitstream_buffer_size= buf_size - current_pos;
}
}
ff_er_frame_end(s);
MPV_frame_end(s);
assert(s->current_picture.pict_type == s->current_picture_ptr->pict_type);
assert(s->current_picture.pict_type == s->pict_type);
if(s->pict_type==B_TYPE || s->low_delay){
*pict= *(AVFrame*)&s->current_picture;
ff_print_debug_info(s, pict);
} else {
*pict= *(AVFrame*)&s->last_picture;
if(pict)
ff_print_debug_info(s, pict);
}
avctx->frame_number = s->picture_number - 1;
if(s->last_picture_ptr || s->low_delay)
*data_size = sizeof(AVFrame);
#ifdef PRINT_FRAME_TIME
printf("%Ld\n", rdtsc()-time);
#endif
return get_consumed_bytes(s, buf_size);
}
| 1threat
|
is it possible to a read the code from an infrared remote controller using a digital camera? : <p>I'm thinking about a simple ceiling fan controlle. A phone camera does "see" the bursts of IR light, is there any Android application to translate it to the hexc code that I could use to make a copy of the controller (or use the phone itself for the task, equipped with an IR emitter)?</p>
| 0debug
|
C#: Regular Expression for specific pattern string : I want to remove particular string using regex from below:
Input string:
{"t":1,"i":"a32dffdd-c99d-4df5-9296-9ae5fb024dc1","p":"At DB Server Time: Wed Sep 27 2017 05:27:18 GMT+0000 (UTC), you sent this message: {\"t\":1,\"i\":\"a32dffdd-c99d-4df5-9296-9ae5fb024dc1\",\"p\":{\"u\":\"/test/delayed\",\"v\":\"GET\",\"h\":{\"X-BH-AgentID\":\"testagent\",\"X-BH-TempToken\":\"testagenttemptoken\"},\"p\":\"\",\"t\":{\"t\":1000}}}"}
----------
Remove below string using regular expression:
At DB Server Time: Wed Sep 27 2017 05:17:01 GMT+0000 (UTC), you sent this message:
I want below output:
{"t":1,"i":"6ca1fca1-c190-40e1-9133-6759bf0c2c95","p":" {\"t\":1,\"i\":\"6ca1fca1-c190-40e1-9133-6759bf0c2c95\",\"p\":{\"u\":\"/test/delayed\",\"v\":\"GET\",\"h\":{\"X-BH-AgentID\":\"testagent\",\"X-BH-TempToken\":\"testagenttemptoken\"},\"p\":\"\",\"t\":{\"t\":1000}}}"}
Thanks in Advanced
1. List item
| 0debug
|
iOS swift NSMutableData has no member appendString : <p>Hello I am new to swift and I am following a tutorial and creating the same code in order to Upload an image . I am now using swift 3 and it seems like <strong>NSMutableData()</strong> no longer has the <strong>appendString</strong> method available what can I do as a substitute ? The tutorial I am following is here <a href="http://swiftdeveloperblog.com/image-upload-example/" rel="noreferrer">http://swiftdeveloperblog.com/image-upload-example/</a> and my code is this</p>
<pre><code>func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString(options: <#T##NSData.Base64EncodingOptions#>)("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
</code></pre>
<p>Again the issue is with the <strong>appendString</strong> as I am getting the error:</p>
<p><em>value of type NSMutableData has no member appendString</em></p>
<p>I been searching for work arounds but have not found any and I have the <strong>append</strong> method available but it does not take a String.</p>
| 0debug
|
trimming a datetime field for an entire column : <p>I have an entire column that I would like to change from a complete datetime field to display only the mm-yyyy.</p>
| 0debug
|
Webpack resolve.alias does not work with typescript? : <p>I try to shorten my imports in typescript</p>
<p>from <code>import {Hello} from "./components/Hello";</code></p>
<p>to <code>import {Hello} from "Hello";</code></p>
<p>For that I found out you can use <code>resolve.alias</code> in webpack thus I configured that part as following</p>
<pre><code>resolve: {
root: path.resolve(__dirname),
alias: {
Hello: "src/components/Hello"
},
extensions: ["", ".ts", ".tsx", ".js"]
},
</code></pre>
<p>Webpack builds, and the output bundle.js works. However typescript's intellisense complain it <code>cannot find the module</code></p>
<p>So my question is whether or not webpack's resolve.alias works with typescript?</p>
<p>I found following <a href="https://github.com/s-panferov/awesome-typescript-loader/issues/34" rel="noreferrer">issue</a> but there's no answer to it.</p>
| 0debug
|
how to move dashboard button to website menu if possible wordpress : <p>I want an easier way for our clients to get to the dashboard, please see the screenshot for reference Thanks.</p>
<p><a href="http://prntscr.com/kzoz4x" rel="nofollow noreferrer">http://prntscr.com/kzoz4x</a></p>
| 0debug
|
I cannot type "@" in a text input after i updated Flash proffesional CC to Animate CC : I cannot type "@" or any other type of special signs into a text input after i updated my flash proffesional.
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.