problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Order of notify handlers : <p>I have a task:</p>
<pre><code>- name: uploads docker configuration file
template:
src: 'docker.systemd.j2'
dest: '/etc/systemd/system/docker.service'
notify:
- daemon reload
- restart docker
</code></pre>
<p>in Ansible playbook's <a href="http://docs.ansible.com/ansible/playbooks_intro.html" rel="noreferrer">documentation</a>, there is a sentence:</p>
<blockquote>
<p>Notify handlers are always run in the order written.</p>
</blockquote>
<p>So, it is expected, that <strong>daemon reload</strong> will be ran before <strong>restart docker</strong>, but in logs, i have:</p>
<pre>
TASK [swarm/docker : uploads docker configuration file] ************************
…
NOTIFIED HANDLER daemon reload
NOTIFIED HANDLER restart docker
…
RUNNING HANDLER [swarm/docker : restart docker] ********************************
…
RUNNING HANDLER [swarm/docker : daemon reload] *********************************
…
</pre>
<p>There are no more "NOTIFIED HANDLER" in logs. Can anyone explain, what i'm doing wrong? :(</p>
| 0debug
|
static int pci_e1000_init(PCIDevice *pci_dev)
{
E1000State *d = DO_UPCAST(E1000State, dev, pci_dev);
uint8_t *pci_conf;
uint16_t checksum = 0;
int i;
uint8_t *macaddr;
pci_conf = d->dev.config;
pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
pci_config_set_device_id(pci_conf, E1000_DEVID);
*(uint16_t *)(pci_conf+0x04) = cpu_to_le16(0x0407);
*(uint16_t *)(pci_conf+0x06) = cpu_to_le16(0x0010);
pci_conf[0x08] = 0x03;
pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);
pci_conf[0x0c] = 0x10;
pci_conf[0x3d] = 1;
d->mmio_index = cpu_register_io_memory(e1000_mmio_read,
e1000_mmio_write, d);
pci_register_bar((PCIDevice *)d, 0, PNPMMIO_SIZE,
PCI_ADDRESS_SPACE_MEM, e1000_mmio_map);
pci_register_bar((PCIDevice *)d, 1, IOPORT_SIZE,
PCI_ADDRESS_SPACE_IO, ioport_map);
memmove(d->eeprom_data, e1000_eeprom_template,
sizeof e1000_eeprom_template);
qemu_macaddr_default_if_unset(&d->conf.macaddr);
macaddr = d->conf.macaddr.a;
for (i = 0; i < 3; i++)
d->eeprom_data[i] = (macaddr[2*i+1]<<8) | macaddr[2*i];
for (i = 0; i < EEPROM_CHECKSUM_REG; i++)
checksum += d->eeprom_data[i];
checksum = (uint16_t) EEPROM_SUM - checksum;
d->eeprom_data[EEPROM_CHECKSUM_REG] = checksum;
d->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_NIC,
d->conf.vlan, d->conf.peer,
d->dev.qdev.info->name, d->dev.qdev.id,
e1000_can_receive, e1000_receive, NULL,
NULL, e1000_cleanup, d);
d->vc->link_status_changed = e1000_set_link_status;
qemu_format_nic_info_str(d->vc, macaddr);
vmstate_register(-1, &vmstate_e1000, d);
e1000_reset(d);
#if 0
if (!pci_dev->qdev.hotplugged) {
static int loaded = 0;
if (!loaded) {
rom_add_option("pxe-e1000.bin");
loaded = 1;
}
}
#endif
return 0;
}
| 1threat
|
find the length of array using map function ES6 : <p>I'm trying to find the length of an array using ES6 using the below code but it does not work.</p>
<pre><code>a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({d[0]:d.length}))
console.log(result)
</code></pre>
<p>This works:-</p>
<pre><code>a=[[1,2,3,4],[4,5,6]]
result = a.map(d=>({name:d[0], length:d.length}))
console.log(result)
</code></pre>
| 0debug
|
static int cow_is_allocated(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, int *num_same)
{
int changed;
if (nb_sectors == 0) {
*num_same = nb_sectors;
return 0;
}
changed = is_bit_set(bs, sector_num);
if (changed < 0) {
return 0;
}
for (*num_same = 1; *num_same < nb_sectors; (*num_same)++) {
if (is_bit_set(bs, sector_num + *num_same) != changed)
break;
}
return changed;
}
| 1threat
|
static void spapr_tce_table_finalize(Object *obj)
{
sPAPRTCETable *tcet = SPAPR_TCE_TABLE(obj);
QLIST_REMOVE(tcet, list);
if (!kvm_enabled() ||
(kvmppc_remove_spapr_tce(tcet->table, tcet->fd,
tcet->nb_table) != 0)) {
g_free(tcet->table);
}
}
| 1threat
|
Using a single coordinates variable to select center in Google Maps JavaScript API : <p>I have a variable called coordinates that is formatted like this:</p>
<p><code>var coordinates = 'lat / lon';</code></p>
<p>I now want to extract the single lat and lon coordinate from that variable to display it as the center in a Google Maps API Map.
I have tried using slice to get the specific parts of the coordinates variable but depending on what coordinate it is the length is different, for example:</p>
<p><code>var coordinates = '49.7824 / 7.2413';</code><br>
<code>var coordinates = '8.5323 / -11.3336';</code></p>
<p>Is there any other way I could use those coordinates as the map center with the Maps API?</p>
| 0debug
|
Show variable image in golang template : Im using a template in a go-lang web application which should show an image depending on which country the visitor is from.
For the images i use the FileServer
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))
In the template the variable country is passed so the application knows which flag to show.
<img id='flag' src='images/{{ .Country}}.png'>
However, for some reason the String i pass adds %0a which causes the src of the img to be wrong.
<img id='flag' src='images/BE%0A.png'>
The expected output should be
<img id='flag' src='images/BE.png'>
The following code is used to grab the country string
resp3, err := http.Get("https://ipinfo.io/country")
if err != nil {
fmt.Println(err)
}
bytes3, _ := ioutil.ReadAll(resp3.Body)
country := string(bytes3)
Could anyone help me resolve this issue?
| 0debug
|
how to use unlink function in php : I Want to use this code update image working fine but. I have need add unlink function this code so please help me ... where add code **unlink function**. I am using PHP 7.2 and database
> Note: the Previous File Delete in a file after update new file
**php update script here...**
<?php
if(isset($_POST['submit']))
{
$sql1 = "SELECT * FROM banner WHERE banner_id='$banner_id'";
$result1 = mysqli_query($conn, $sql1);
mysqli_num_rows($result1) > 0;
$row1 = mysqli_fetch_assoc($result1);
$fileinfo = @getimagesize($_FILES["image"]["tmp_name"]);
$width = $fileinfo[0];
$height = $fileinfo[1];
if(!empty($_FILES['image'] ['name'])) {
$extension = pathinfo($_FILES['image'] ['name'], PATHINFO_EXTENSION);
$image = "Banner".'-'. rand(10000,99999) . '.' . $extension;
}
if (($_FILES["image"]["size"] > 2000000)) {
$response = array(
"type" => "error",
$_SESSION['msg1'] = "Image size exceeds 2MB" );
} else if ($width < "900" || $height < "250") {
$response = array(
"type" => "error",
$_SESSION['msg2'] = "the image should be used greater than 900 X 250 "
);
} else {
$location = "../image/banner/".$image;
if(in_array(strtolower($extension), [ 'png', 'jpeg', 'jpg', ])){
compressImage($_FILES['image']['tmp_name'],$location,60);}
else{$image=$row1['image'];}
$sql=mysqli_query($conn,"update banner set Image='$image' where
banner_id='$banner_id' ");
$_SESSION['msg']="Successfully Banner Image Updated Successfully !!";
}
}
?>
| 0debug
|
Why won't this code run? I am confused : <pre><code>// main.cpp
#include <iostream>
#include "add.h"
int main(){
std::cout << "Hello World\n";
std::cout << add(3,4) << std::endl;
return 0;
}
// add.h
#ifndef add_h
#define add_h
int add(int x, int y);
#endif /* add_h */
// add.cpp
#include "add.h"
int add(int x, int y){
return x + y;
}
</code></pre>
<p>I am compiling with 'g++ -std=c++11 main.cpp -o main'. I keep getting linker errors. I copied it exactly from a tutorial too.</p>
| 0debug
|
static int fbdev_read_packet(AVFormatContext *avctx, AVPacket *pkt)
{
FBDevContext *fbdev = avctx->priv_data;
int64_t curtime, delay;
struct timespec ts;
int i, ret;
uint8_t *pin, *pout;
if (fbdev->time_frame == AV_NOPTS_VALUE)
fbdev->time_frame = av_gettime();
while (1) {
curtime = av_gettime();
delay = fbdev->time_frame - curtime;
av_dlog(avctx,
"time_frame:%"PRId64" curtime:%"PRId64" delay:%"PRId64"\n",
fbdev->time_frame, curtime, delay);
if (delay <= 0) {
fbdev->time_frame += INT64_C(1000000) * av_q2d(fbdev->time_base);
break;
}
if (avctx->flags & AVFMT_FLAG_NONBLOCK)
return AVERROR(EAGAIN);
ts.tv_sec = delay / 1000000;
ts.tv_nsec = (delay % 1000000) * 1000;
while (nanosleep(&ts, &ts) == EINTR);
}
if ((ret = av_new_packet(pkt, fbdev->frame_size)) < 0)
return ret;
if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0)
av_log(avctx, AV_LOG_WARNING,
"Error refreshing variable info: %s\n", strerror(errno));
pkt->pts = curtime;
pin = fbdev->data + fbdev->bytes_per_pixel * fbdev->varinfo.xoffset +
fbdev->varinfo.yoffset * fbdev->fixinfo.line_length;
pout = pkt->data;
for (i = 0; i < fbdev->heigth; i++) {
memcpy(pout, pin, fbdev->frame_linesize);
pin += fbdev->fixinfo.line_length;
pout += fbdev->frame_linesize;
}
return fbdev->frame_size;
}
| 1threat
|
static pcibus_t pci_bar_address(PCIDevice *d,
int reg, uint8_t type, pcibus_t size)
{
pcibus_t new_addr, last_addr;
int bar = pci_bar(d, reg);
uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
if (type & PCI_BASE_ADDRESS_SPACE_IO) {
if (!(cmd & PCI_COMMAND_IO)) {
return PCI_BAR_UNMAPPED;
}
new_addr = pci_get_long(d->config + bar) & ~(size - 1);
last_addr = new_addr + size - 1;
if (last_addr <= new_addr || new_addr == 0 || last_addr >= UINT32_MAX) {
return PCI_BAR_UNMAPPED;
}
return new_addr;
}
if (!(cmd & PCI_COMMAND_MEMORY)) {
return PCI_BAR_UNMAPPED;
}
if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
new_addr = pci_get_quad(d->config + bar);
} else {
new_addr = pci_get_long(d->config + bar);
}
if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
return PCI_BAR_UNMAPPED;
}
new_addr &= ~(size - 1);
last_addr = new_addr + size - 1;
if (last_addr <= new_addr || new_addr == 0 ||
last_addr == PCI_BAR_UNMAPPED) {
return PCI_BAR_UNMAPPED;
}
if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
return PCI_BAR_UNMAPPED;
}
if (last_addr >= HWADDR_MAX) {
return PCI_BAR_UNMAPPED;
}
return new_addr;
}
| 1threat
|
Hot to get the next value from array of a hash : **File: database.rb** Here I connect to the database and loop over the rows in table `rcpt`. Then I store the value in `row["email"]`. The table stores two values: `id` with primary key, auto_increment and `email`.
require 'mysql2'
class Db
def con
@db_host = "localhost"
@db_user = "root"
@db_pass = "password"
@db_name = "table_db"
client = Mysql2::Client.new(:host => @db_host, :unsername => @db_user, :password => @db_pass, :database => @db_name)
rcpt = client.query("SELECT * from rcpt")
rcpt.each do |row|
row["email"]
end
end
end
Ouput of `con` method without ["email"]:
{"id"=>01, "email"=>"example1@example.com"}
{"id"=>02, "email"=>"example2@example.com"}
Output of `con` method with ["email"]:
example1@example.com
example2@example.com
**File: message_class.rb** Here I create the method `pull_rcpt` which then stores `row["email"]`. Then I'm trying to use the `pull_rcpt` method in `message` heredoc. Now comes my problem: in the `To:` field, I'm trying to pass the users email address I'm currently sending to, so it should change with the receiving email address. It still uses the email address of the first contact in the array/Db. What am I doing wrong?
require 'dkim'
require './database'
class Email
def pull_rcpt
rcpt = Db.new
rcpt.con
end
def data
Dkim::domain = 'example.com'
Dkim::selector = 'mail'
Dkim::private_key = open('/path/to/keys/example.com/mail.private').read
message = <<~MESSAGE
From: Eva <test@example.com>
To: Dani <#{pull_rcpt[0]["email"]}>
MIME-Version: 1.0
Content-Type: text/html
Content-Transfer-Encoding: 8bit
Subject: Test Subject
This is an email message.
<h1>Test</h1>
MESSAGE
end
end
**File: mailer.rb** In my mailer_class I have two method's `rcpt_to` and `message` which contains an array `contacts`, which holds the values of `row["email"]`.
def rcpt_to
#conn zu DB & take rcpt
contacts = []
contacts = Db.new
contacts.con
end
def message
#message
message = Email.new
end
A few lines later I use the methods as follows:
@protocol = {rcpt_to: [rcpt["email"]], data: Dkim.sign(message.data)}
Here is the email raw header from the second email address/value in the database:
From: Eva <test@example.com>
To: Dani <example1@example.com> <--- This should be example2(second value in hash and second entry in database) not example1
MIME-Version: 1.0
Content-Type: text/html
Content-Transfer-Encoding: 8bit
Subject: Test Subject
Content-Length: 40
Any help would be appreciated. Thanks in advance. Sorry for my language, its not my native.
| 0debug
|
static void memory_region_dispatch_write(MemoryRegion *mr,
hwaddr addr,
uint64_t data,
unsigned size)
{
if (!memory_region_access_valid(mr, addr, size, true)) {
return;
}
adjust_endianness(mr, &data, size);
if (!mr->ops->write) {
mr->ops->old_mmio.write[bitops_ctzl(size)](mr->opaque, addr, data);
return;
}
access_with_adjusted_size(addr, &data, size,
mr->ops->impl.min_access_size,
mr->ops->impl.max_access_size,
memory_region_write_accessor, mr);
}
| 1threat
|
I'm getting a "Parse error: syntax error, unexpected ')'", not sure why : <p>I'm trying to change the look of a button based on whether the user has liked an image by using 1 class if he has and another class if he hasn't but I'm getting a parse error which I can not find. Of course the reason could be that I'm trying to do something that can't be done like that.</p>
<pre><code><a href='#' class='vote {{ Auth::user()->votes()->where("image_id", $image->id)->first() ? Auth::user()->votes()->where("image_id", $image->id)->first()->like == 1 ? "liked" : "like" }}' id='{{$image->id}}'></a>
</code></pre>
| 0debug
|
How to fix modules with "ModuleConcatenation bailout: Module is not an ECMAScript module" bailout message? : <p>Webpack3 comes with the <code>ModuleConcatenation</code> plugin that when used with the <code>--display-optimization-bailout</code> flag will give you the reason for bailout.</p>
<p>The bailout messages not that easy to understand, and it's hard to understand why they happened to a specific module.</p>
<p>Here is my output for the <code>webpack</code> command on a very simplified version of my project:</p>
<pre><code>> webpack --bail --display-optimization-bailout
Hash: 4a9a55dc2883e82a017e
Version: webpack 3.4.1
Child client:
Hash: 4a9a55dc2883e82a017e
Time: 594ms
Asset Size Chunks Chunk Names
a.d3ade61d21d5cb8dd426.bundle.js 712 bytes 0 [emitted] a
a.d3ade61d21d5cb8dd426.bundle.js.map 6.57 kB 0 [emitted] a
manifest.json 102 bytes [emitted]
index.html 299 kB [emitted] [big]
[0] multi ./src/client/bootstrap/ErrorTrap.js 28 bytes {0} [built]
ModuleConcatenation bailout: Module is not an ECMAScript module
[1] ./src/client/bootstrap/ErrorTrap.js 199 bytes {0} [built]
ModuleConcatenation bailout: Module is not an ECMAScript module
</code></pre>
<p>I simplified the contents of <code>./src/client/bootstrap/ErrorTrap.js</code> as much as I could, and I still get the <code>ModuleConcatenation bailout: Module is not an ECMAScript module</code>. Here are its contents:</p>
<pre><code>class ErrorTrap {
}
export default ErrorTrap;
</code></pre>
<p>I looked into understanding this bailout message, and one of the reasons it happens is when the module doesn't have imports or exports, as seen at <a href="https://github.com/webpack/webpack/blob/93ac8e9c3699bf704068eaccaceec57b3dd45a14/lib/dependencies/HarmonyDetectionParserPlugin.js#L12-L14" rel="noreferrer">https://github.com/webpack/webpack/blob/93ac8e9c3699bf704068eaccaceec57b3dd45a14/lib/dependencies/HarmonyDetectionParserPlugin.js#L12-L14</a>, but I don't know why it's not considering this module a <code>ECMAScript</code> module.</p>
<p><strong>.babelrc</strong></p>
<pre><code>{
"presets": [
"es2015"
]
}
</code></pre>
<p><strong>webpack.config.js</strong> representation:</p>
<pre><code>{ target: 'web',
devtool: 'source-map',
entry: { a: [ './src/client/bootstrap/ErrorTrap.js' ] },
output:
{ path: '/project/build/client/assets',
filename: '[name].[chunkhash].bundle.js',
chunkFilename: '[name].[chunkhash].chunk.js',
publicPath: '/assets/' },
module: { rules: [ [Object], [Object], [Object], [Object], [Object] ] },
resolve: { alias: { 'lodash.defaults': 'lodash' } },
plugins:
[ ModuleConcatenationPlugin { options: {} },
CommonsChunkPlugin {
chunkNames: [Object],
filenameTemplate: undefined,
minChunks: Infinity,
selectedChunks: undefined,
children: undefined,
async: undefined,
minSize: undefined,
ident: '/project/node_modules/webpack/lib/optimize/CommonsChunkPlugin.js0' },
ManifestPlugin { opts: [Object] },
ChunkManifestPlugin {
manifestFilename: 'chunk-manifest.json',
manifestVariable: 'webpackManifest',
inlineManifest: false },
OccurrenceOrderPlugin { preferEntry: undefined },
DefinePlugin { definitions: [Object] },
VisualizerPlugin { opts: [Object] },
ExtractTextPlugin { filename: '[name].[contenthash].css', id: 1, options: {} },
UglifyJsPlugin { options: [Object] },
LoaderOptionsPlugin { options: [Object] } ],
name: 'client' }
</code></pre>
| 0debug
|
static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < ETH_MAX_L2_HDR_LEN) {
l2_hdr->iov_len = 0;
return false;
} else {
l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
switch (l3_proto) {
case ETH_P_IP:
l3_hdr->iov_base = g_malloc(ETH_MAX_IP4_HDR_LEN);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, sizeof(struct ip_header));
if (bytes_read < sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
vmxnet_tx_pkt_calculate_hdr_len(pkt);
pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base);
return true;
}
| 1threat
|
Go; call operator by name : what is the golang equivelent of python's `operator` package for calling builtin operators by name?
https://docs.python.org/3.4/library/operator.html
Meaning, how can I do something like
```
func f(op func(int, int)bool, a int, b int)
return op(a, b)
f(operators.LessThan, 1, 2) // true
```
| 0debug
|
static void qemu_cpu_kick_thread(CPUState *env)
{
#ifndef _WIN32
int err;
err = pthread_kill(env->thread->thread, SIG_IPI);
if (err) {
fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
exit(1);
}
#else
if (!qemu_cpu_is_self(env)) {
SuspendThread(env->thread->thread);
cpu_signal(0);
ResumeThread(env->thread->thread);
}
#endif
}
| 1threat
|
Python. How i can iterate over tuples with dict inside : I have some dicts inside tuple
a = ({'row_n': 1, 'row_section': None, 'nomenclature_platform_id': 'qwe', 'nomenclature_name': 'name', 'TM': ' ', 'no_category': 'orig_num Номер', 'article': 'num артикля', 'size_measures_multi': [('1', 'cm', 'brutto'), ('123', 'm', 'netto_brutto_unknown'), ('1233', 'm', 'netto_brutto_unknown')]}, {'row_n': 2, 'row_section': None, 'nomenclature_platform_id': '34110', 'nomenclature_name': 'Fuel MAX', 'TM': 'Fuel MAX', 'no_category': 'MAGNETICYW', 'article': 'MAGNETICYW', 'size_measures_multi': [('1', 'm', 'netto_brutto_unknown'), ('21', 'm', 'netto_brutto_unknown'), ('28', 'm', 'netto_brutto_unknown')]})
I wont make tuples from key nomenclature_platform_id and every first element from list of tuples, which contain in key 'size_measures_multi', for example
> ('qwe', '1', '123', '1233')
> ('34110', '1','21','28')
I try make list comprihansion inside tuple
tuple(a['nomenclature_platform_id'], [item[0] for item in row['size_measures_multi']])
But i have not expected result
> ('qwe', ['1', '123', '1233'])
> ('34110', ['1','21','28'])
Why my code work wrong and how i can fix it? I will be grateful for the help
| 0debug
|
visual studio sort order : <p>I have a C# app in Visual studio coded. One of the parts of this app is to sort coupons. Right now, coupons are sorted in descending order by end date. There is an option already in there to make coupons exclusive offers. I was wondering if there was a way to sort coupons by sort order, then by exlusivity, and then by the end date.</p>
<p>Here is a sample of the code:</p>
<pre><code>var allLocalCoupons = merchant.Coupons
.Where(c => c.IsActive
&& c.StartDate <= DateTime.Now
&& (c.EndDate > DateTime.Now || c.EndDate == null)
&& (c.ExclusiveCouponOffer == ApplicationCode ||
c.ExclusiveCouponOffer == null))
.OrderBy(c => c.EndDate)
.ToList();
</code></pre>
| 0debug
|
it doesn't apper add import java.util.Scanner : <p>I'm learning to "code", when i try to write the class Scanner it doesnt recognize the word, in the class that I'm taking shows that I need to add import java util scanner, but it doesn't appear in my options when a press right click,</p>
<p>the same problem happens with "var"</p>
<p>Thank you so much for your help.</p>
<p><a href="https://i.stack.imgur.com/R2zil.png" rel="nofollow noreferrer">enter image description here</a></p>
| 0debug
|
Spark convert rdd to datadrame : i'm using spark 1.6 with scala, i have a big file , after filtring the first lines that containes some copy rights i want to take the header (104 fields) and convert it to StructType schema.
i was thinking to use a class extends Product trait to define to schema of the dataframe and than convert it to dataframe According to that shema.
What is the best way to do it.
this is a sample from my file :
text (06.07.03.216) COPYRIGHT © skdjh 2000-2016
text 160614_54554.vf Database 53643_csc Interface 574 zn 65
Start Date 14/06/2016 00:00:00:000
End Date 14/06/2016 00:14:59:999
State "s23"
cin. Nb Start End Event Con. Duration IMSI
32055680 16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
32055680 16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
32055680 16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
32055680 16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
32055680 16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
i want to convert it to spark sql like this schema
----------------------------------------------------------------------------------------
| cin_Nb | Start | End | Event | Con_Duration | IMSI |
| ----------------------------------------------------------------------------------------|
| 32055680 | 16/09/2010 | 16:59:59:245 | 16/09/2016 | 17:00:00:000 | xxxxx |
| 32055680 | 16/09/2010 | 16:59:59:245 | 16/09/2016 | 17:00:00:000 | xxxxx |
| 32055680 | 16/09/2010 | 16:59:59:245 | 16/09/2016 | 17:00:00:000 | xxxxx |
| 20556800 | 16/09/2010 | 16:59:59:245 | 16/09/2016 | 17:00:00:000 | xxxxx |
| 32055680 | 16/09/2010 | 16:59:59:245 | 16/09/2016 | 17:00:00:000 | xxxxx |
----------------------------------------------------------------------------------------
Thank you
| 0debug
|
Reading chrome's ctrl+p data : <p>Is it possible with chrome extension to read ctrl+p data and save it as pdf or html without showing print screen?</p>
| 0debug
|
Python Requests - Dynamically Pass HTTP Verb : <p>Is there a way to pass an HTTP verb (PATCH/POST) to a function and dynamically use that verb for Python requests?</p>
<p>For example, I want this function to take a 'verb' variable which is only called internally and will either = post/patch.</p>
<pre><code>def dnsChange(self, zID, verb):
for record in config.NEW_DNS:
### LINE BELOW IS ALL THAT MATTERS TO THIS QUESTION
json = requests.verb(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]})
key = record[0] + "record with host " + record[1]
result = json.loads(json.text)
self.apiSuccess(result,key,value)
</code></pre>
<p>I realize I cannot requests.'verb' as I have above, it's meant to illustrate the question. Is there a way to do this or something similar? I'd like to avoid an:</p>
<pre><code>if verb == 'post':
json = requests.post(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
else:
json = requests.patch(headers=self.auth, url=self.API + '/zones/' + str(zID) + '/dns_records', data={"type":record[0], "name":record[1], "content":record[2]}
</code></pre>
<p>Thanks guys!</p>
| 0debug
|
How do I remove zeros between my outputs? : <pre><code>bool getAnswer(int a);
int main ()
{
string questions[5] = {"CPU stands for 'Central Processing Unit'", "RAM stands for 'Reserved Access Main'", "HDD stands for 'Hard Drive Doubler'", "SSD stands for 'Solid State Drive'", "CPP stands for 'C Programming Plus'"};
for (int i = 0; i < 5; i++)
{
cout << "Question " << ++i << " \n";
i--;
cout << questions[i] << "\n";
cout << getAnswer(i) << endl;
}
}
bool getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
cout << "Answer " << ++a << " \n";
a--;
cout << "Enter a true or false answer: " << "\n";
cin >> input;
while (input != "T" && input != "t" && input != "F" && input != "f" && input != "True" && input != "true" && input != "False" && input != "false")
{
cout << "Invalid entry, try again!\nEnter a true or false answer: " << "\n";
cin >> input;
}
if (input == "T" || input == "t" || input == "True" || input == "true")
{
user[a] = true;
}
else if (input == "F" || input == "f" || input == "False" || input == "false")
{
user[a] = false;
}
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
}
</code></pre>
<p>In the output between the correct/incorrect and next question, I keep getting a "0" in-between. How do i remove them. </p>
<p>Ex:
Question 1<br>
CPU stands for 'Central Processing Unit'<br>
Answer 1<br>
Enter a true or false answer:<br>
f<br>
Incorrect!<br>
0<br>
Question 2<br>
RAM stands for 'Reserved Access Main'<br>
Answer 2<br>
Enter a true or false answer:<br>
t<br>
Incorrect!<br>
0</p>
| 0debug
|
Subset column and compute operations for each subset : <p>Here is a minimal example of dataframe to reproduce.</p>
<pre><code>df <- structure(list(Gene = structure(c(147L, 147L, 148L, 148L, 148L,
87L, 87L, 87L, 87L, 87L), .Label = c("genome", "k141_1189_101",
"k141_1189_104", "k141_1189_105", "k141_1189_116", "k141_1189_13",
"k141_1189_14", "k141_1189_146", "k141_1189_150", "k141_1189_18",
"k141_1189_190", "k141_1189_194", "k141_1189_215", "k141_1189_248",
"k141_1189_251", "k141_1189_252", "k141_1189_259", "k141_1189_274",
"k141_1189_283", "k141_1189_308", "k141_1189_314", "k141_1189_322",
"k141_1189_353", "k141_1189_356", "k141_1189_372", "k141_1189_373",
"k141_1189_43", "k141_1189_45", "k141_1189_72", "k141_1597_15",
"k141_1597_18", "k141_1597_23", "k141_1597_41", "k141_1597_55",
"k141_1597_66", "k141_1597_67", "k141_1597_68", "k141_1597_69",
"k141_2409_34", "k141_2409_8", "k141_3390_69", "k141_3390_83",
"k141_3390_84", "k141_3726_25", "k141_3726_31", "k141_3726_49",
"k141_3726_50", "k141_3726_62", "k141_3726_8", "k141_3726_80",
"k141_3790_1", "k141_3993_114", "k141_3993_122", "k141_3993_162",
"k141_3993_172", "k141_3993_183", "k141_3993_186", "k141_3993_188",
"k141_3993_24", "k141_3993_25", "k141_3993_28", "k141_3993_32",
"k141_3993_44", "k141_3993_47", "k141_3993_53", "k141_3993_57",
"k141_3993_68", "k141_4255_80", "k141_4255_81", "k141_4255_87",
"k141_5079_107", "k141_5079_110", "k141_5079_130", "k141_5079_14",
"k141_5079_141", "k141_5079_16", "k141_5079_184", "k141_5079_185",
"k141_5079_202", "k141_5079_24", "k141_5079_39", "k141_5079_63",
"k141_5079_65", "k141_5079_70", "k141_5079_77", "k141_5079_87",
"k141_5079_9", "k141_5313_16", "k141_5313_17", "k141_5313_20",
"k141_5313_23", "k141_5313_39", "k141_5313_5", "k141_5313_51",
"k141_5313_52", "k141_5313_78", "k141_5545_101", "k141_5545_103",
"k141_5545_104", "k141_5545_105", "k141_5545_106", "k141_5545_107",
"k141_5545_108", "k141_5545_109", "k141_5545_110", "k141_5545_111",
"k141_5545_112", "k141_5545_113", "k141_5545_114", "k141_5545_119",
"k141_5545_128", "k141_5545_130", "k141_5545_139", "k141_5545_141",
"k141_5545_145", "k141_5545_16", "k141_5545_169", "k141_5545_17",
"k141_5545_172", "k141_5545_6", "k141_5545_60", "k141_5545_62",
"k141_5545_63", "k141_5545_86", "k141_5545_87", "k141_5545_88",
"k141_5545_89", "k141_5545_91", "k141_5545_92", "k141_5545_93",
"k141_5545_94", "k141_5545_96", "k141_5545_97", "k141_5545_98",
"k141_5545_99", "k141_5734_13", "k141_5734_2", "k141_5734_4",
"k141_5734_5", "k141_5734_6", "k141_6014_124", "k141_6014_2",
"k141_6014_34", "k141_6014_75", "k141_6014_96", "k141_908_14",
"k141_908_2", "k141_908_5", "k141_957_126", "k141_957_135", "k141_957_136",
"k141_957_14", "k141_957_140", "k141_957_141", "k141_957_148",
"k141_957_179", "k141_957_191", "k141_957_35", "k141_957_47",
"k141_957_55", "k141_957_57", "k141_957_59", "k141_957_6", "k141_957_63",
"k141_957_65", "k141_957_68", "k141_957_77", "k141_957_95"), class = "factor"),
depth = c(9L, 10L, 9L, 10L, 11L, 14L, 15L, 16L, 17L, 18L),
bases_covered = c(6L, 3L, 4L, 7L, 4L, 59L, 54L, 70L, 34L,
17L), gene_length = c(1140L, 1140L, 591L, 591L, 591L, 690L,
690L, 690L, 690L, 690L), regioncoverage = c(54L, 30L, 36L,
70L, 44L, 826L, 810L, 1120L, 578L, 306L)), .Names = c("Gene",
"depth", "bases_covered", "gene_length", "regioncoverage"), row.names = c(1L,
2L, 33L, 34L, 35L, 78L, 79L, 80L, 81L, 82L), class = "data.frame")
</code></pre>
<p>The dataframe looks like this:</p>
<pre><code> Gene depth bases_covered gene_length regioncoverage
1 k141_908_2 9 6 1140 54
2 k141_908_2 10 3 1140 30
33 k141_908_5 9 4 591 36
34 k141_908_5 10 7 591 70
35 k141_908_5 11 4 591 44
78 k141_5079_9 14 59 690 826
79 k141_5079_9 15 54 690 810
80 k141_5079_9 16 70 690 1120
81 k141_5079_9 17 34 690 578
82 k141_5079_9 18 17 690 306
</code></pre>
<p>What i want is that for each Gene (e.g k141_908_2) i want to sum region coverage and divide by unique(gene length). In fact gene length is always the same value for each gene.</p>
<p>For example for Gene K141_908_2 i would do: (54+30)/1140 = 0.07
For example for Gene K141_908_5 i would do: (36+70+44)/591 = 0.25</p>
<p>The final dataframe should report two columns.</p>
<pre><code> Gene Newcoverage
1 k141_908_2 0.07
2 k141_908_5 0.25
3 ......
</code></pre>
<p>and so on .</p>
<p>Thanks for your help</p>
| 0debug
|
MongoError: Unknown modifier: $pushAll in node js : <p>I am having an issue when saving a model fails with <strong>mongo error: MongoError: Unknown modifier: $pushAll</strong>.</p>
<p>I have one array field <code>subDomains</code> in my schema and which will get saved as default with subdomain as like follows.</p>
<pre><code> // already Domain instance get availble
Domain.subDomains.push({'name': 'default' , 'role': 'xyz', ...});
// save domain with default fileds
Domain.save()
</code></pre>
<p>System Info as like as follows:</p>
<pre><code> ➜ ~ node --version
v9.4.0
➜ ~ npm --version
5.6.0
➜ ~
➜ ~ mongo --version
MongoDB shell version v3.6.2
git version: ......
OpenSSL version: OpenSSL 1.0.2n 7 Dec 2017
allocator: system
modules: none
build environment:
distarch: x86_64
target_arch: x86_64
➜ ~
</code></pre>
<p>Please help me to sort out this one.</p>
| 0debug
|
Why do both Promise's then & catch callbacks get called? : <p>I have the following code and when it's executed, it returns both "<strong>rejected</strong>" and "<strong>success</strong>":</p>
<pre><code>// javascript promise
var promise = new Promise(function(resolve, reject){
setTimeout(function(){reject()}, 1000)
});
promise
.catch(function(){console.log('rejected')})
.then(function(){console.log('success')});
</code></pre>
<p>Could anyone explain <strong>why success is logged?</strong></p>
| 0debug
|
Android cannot resolve Material Components : <p>I am getting this error:</p>
<blockquote>
<p>Cannot resolve symbol
'@style/Widget.MaterialComponents.TextInputLayout.OutlineBox'</p>
</blockquote>
<p>I am getting this error after I added this line to my TextInputLayout in my XML:</p>
<pre><code>style="@style/Widget.MaterialComponents.TextInputLayout.OutlineBox"
</code></pre>
<p>This is my full XML code(removed unrelevant constraints/margins):</p>
<pre><code><android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlineBox"
android:layout_width="match_parent"
android:layout_height="0dp"
app:counterEnabled="true"
app:counterMaxLength="300">
<android.support.design.widget.TextInputEditText
android:id="@+id/cheese_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start"
android:hint="@string/cheese_description" />
</android.support.design.widget.TextInputLayout>
</code></pre>
<p>this is my app <strong>build.gradle</strong>:</p>
<pre><code> apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "app.cheese.cheese.some.sample_cheese"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildToolsVersion '27.0.3'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.android.support:design:27.0.2'
compile 'com.google.firebase:firebase-core:11.8.0'
implementation 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support:support-v4:27.0.2'
compile 'com.google.firebase:firebase-storage:11.8.0'
compile 'com.google.firebase:firebase-messaging:11.8.0'
compile 'com.firebaseui:firebase-ui-auth:3.1.3'
compile 'com.google.firebase:firebase-database:11.8.0'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
implementation 'com.firebaseui:firebase-ui-database:3.2.1'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
<p>and this is my other <strong>build.gradle</strong>:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "https://maven.google.com"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p>I tried:</p>
<ul>
<li>changing buildToolsVersions from "27.0.3" to "27.0.2" and sync</li>
<li>Invalidate Caches/ Restart</li>
<li>Rebuild Project</li>
</ul>
<p>I took the XML line of code that causes error <a href="https://material.io/components/android/catalog/text-input-layout/" rel="noreferrer">from the material.io components here</a>. does anyone know what I am doing wrong?</p>
<p>Thank you :)</p>
| 0debug
|
I wanna replace the % mark to - this mark of url : <p>I wanna replace the % mark to - this mark of url </p>
<p>from </p>
<blockquote>
<p>`<a href="http://localhost/news/news/6/1/my%news%of%bangla" rel="nofollow">http://localhost/news/news/6/1/my%news%of%bangla</a>
to</p>
<p><a href="http://localhost/news/news/6/1/my-news-of-bangla" rel="nofollow">http://localhost/news/news/6/1/my-news-of-bangla</a></p>
</blockquote>
| 0debug
|
where can we use "try catch" and exception? : <p>How to throw a C++ exception
c++ exception-handling
I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).</p>
<p>For example, I have defined a function as follows: int compare(int a, int b){...}</p>
<p>I'd like the function to throw an exception with some message when either a or b is negative.</p>
<p>How should I approach this in the definition of the function?</p>
| 0debug
|
int ff_init_filters(SwsContext * c)
{
int i;
int index;
int num_ydesc;
int num_cdesc;
int num_vdesc = isPlanarYUV(c->dstFormat) && !isGray(c->dstFormat) ? 2 : 1;
int need_lum_conv = c->lumToYV12 || c->readLumPlanar || c->alpToYV12 || c->readAlpPlanar;
int need_chr_conv = c->chrToYV12 || c->readChrPlanar;
int srcIdx, dstIdx;
int dst_stride = FFALIGN(c->dstW * sizeof(int16_t) + 66, 16);
uint32_t * pal = usePal(c->srcFormat) ? c->pal_yuv : (uint32_t*)c->input_rgb2yuv_table;
int res = 0;
if (c->dstBpc == 16)
dst_stride <<= 1;
num_ydesc = need_lum_conv ? 2 : 1;
num_cdesc = need_chr_conv ? 2 : 1;
c->numSlice = FFMAX(num_ydesc, num_cdesc) + 2;
c->numDesc = num_ydesc + num_cdesc + num_vdesc;
c->descIndex[0] = num_ydesc;
c->descIndex[1] = num_ydesc + num_cdesc;
c->desc = av_mallocz_array(sizeof(SwsFilterDescriptor), c->numDesc);
if (!c->desc)
return AVERROR(ENOMEM);
c->slice = av_mallocz_array(sizeof(SwsSlice), c->numSlice);
res = alloc_slice(&c->slice[0], c->srcFormat, c->srcH, c->chrSrcH, c->chrSrcHSubSample, c->chrSrcVSubSample, 0);
if (res < 0) goto cleanup;
for (i = 1; i < c->numSlice-2; ++i) {
res = alloc_slice(&c->slice[i], c->srcFormat, c->vLumFilterSize + MAX_LINES_AHEAD, c->vChrFilterSize + MAX_LINES_AHEAD, c->chrSrcHSubSample, c->chrSrcVSubSample, 0);
if (res < 0) goto cleanup;
res = alloc_lines(&c->slice[i], FFALIGN(c->srcW*2+78, 16), c->srcW);
if (res < 0) goto cleanup;
}
res = alloc_slice(&c->slice[i], c->srcFormat, c->vLumFilterSize + MAX_LINES_AHEAD, c->vChrFilterSize + MAX_LINES_AHEAD, c->chrDstHSubSample, c->chrDstVSubSample, 1);
if (res < 0) goto cleanup;
res = alloc_lines(&c->slice[i], dst_stride, c->dstW);
if (res < 0) goto cleanup;
fill_ones(&c->slice[i], dst_stride>>1, c->dstBpc == 16);
++i;
res = alloc_slice(&c->slice[i], c->dstFormat, c->dstH, c->chrDstH, c->chrDstHSubSample, c->chrDstVSubSample, 0);
if (res < 0) goto cleanup;
index = 0;
srcIdx = 0;
dstIdx = 1;
if (need_lum_conv) {
ff_init_desc_fmt_convert(&c->desc[index], &c->slice[srcIdx], &c->slice[dstIdx], pal);
c->desc[index].alpha = c->alpPixBuf != 0;
++index;
srcIdx = dstIdx;
}
dstIdx = FFMAX(num_ydesc, num_cdesc);
ff_init_desc_hscale(&c->desc[index], &c->slice[index], &c->slice[dstIdx], c->hLumFilter, c->hLumFilterPos, c->hLumFilterSize, c->lumXInc);
c->desc[index].alpha = c->alpPixBuf != 0;
++index;
{
srcIdx = 0;
dstIdx = 1;
if (need_chr_conv) {
ff_init_desc_cfmt_convert(&c->desc[index], &c->slice[srcIdx], &c->slice[dstIdx], pal);
++index;
srcIdx = dstIdx;
}
dstIdx = FFMAX(num_ydesc, num_cdesc);
if (c->needs_hcscale)
ff_init_desc_chscale(&c->desc[index], &c->slice[srcIdx], &c->slice[dstIdx], c->hChrFilter, c->hChrFilterPos, c->hChrFilterSize, c->chrXInc);
else
ff_init_desc_no_chr(&c->desc[index], &c->slice[srcIdx], &c->slice[dstIdx]);
}
++index;
{
srcIdx = c->numSlice - 2;
dstIdx = c->numSlice - 1;
ff_init_vscale(c, c->desc + index, c->slice + srcIdx, c->slice + dstIdx);
}
return 0;
cleanup:
ff_free_filters(c);
return res;
}
| 1threat
|
How computer understands Natural Language : <p>I want to build an application which takes story as input later it has to tell the answers from that story. I want to know how AI understands English how to store the story in AI</p>
| 0debug
|
How to perfectly align an unequal number of plots (ggplot2,gridExtra) : <p>I would like to perfectly align these plots :</p>
<p><a href="https://i.stack.imgur.com/sxwpj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sxwpj.png" alt="unaligned plots"></a></p>
<p>Here is the R code :</p>
<pre><code>library(tidyverse)
library(gridExtra)
groupes <- tribble(~type, ~group, ~prof, ~var,
1,1,1,12,
1,1,2,-24,
1,2,1,-11,
1,2,2,7,
2,1,1,10,
2,1,2,5,
2,2,1,-25,
2,2,2,2,
2,3,1,10,
2,3,2,3,
3,1,1,10,
3,1,2,-5,
3,2,1,25,
3,2,2,2,
3,3,1,-10,
3,3,2,3,
3,4,1,25,
3,4,2,-18)
hlay <- rbind(c(1,2,3),
c(1,2,3),
c(NA,2,3),
c(NA,NA,3))
p1 <- groupes %>% filter(type==1) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
coord_cartesian(ylim=c(-25,25)) +
labs(title="type 1",x="",y="")
p2 <- groupes %>% filter(type==2) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
coord_cartesian(ylim=c(-25,25)) +
labs(title="type 2",x="",y="")
p3 <- groupes %>% filter(type==3) %>% ggplot(aes(prof,var)) + geom_col() + facet_wrap(~group,ncol=1) +
coord_cartesian(ylim=c(-25,25)) +
labs(title="type 3",x="",y="")
grid.arrange(p1,p2,p3, layout_matrix=hlay)
</code></pre>
<p>I may succeed to produce a better alignment by adding <code>heights=c(1.3,1,1,1)</code> into <code>grid.arrange</code> but that is not a perfect solution. Another solution would be not to take into account the space taken by the labels, but I do not know how to do that.</p>
| 0debug
|
What is the difference between destructured assignment and "normal" assignment? : <p>I was playing around in the python 2.7.6 REPL and came across this behavior.</p>
<pre><code>>>> x = -10
>>> y = -10
>>> x is y
False
>>> x, y = [-10, -10]
>>> x is y
True
</code></pre>
<p>It seems that destructured assignment returns the same reference for equivalent values. Why is this?</p>
| 0debug
|
ES6 map an array of objects, to return an array of objects with new keys : <p>I have an array of objects:</p>
<pre><code>[
{
id: 1,
name: 'bill'
},
{
id: 2,
name: 'ted'
}
]
</code></pre>
<p>Looking for a simple one-liner to return:</p>
<pre><code>[
{
value: 1,
text: 'bill'
},
{
value: 2,
text: 'ted'
}
]
</code></pre>
<p>So I can easily pump them into a react dropdown with the proper keys. </p>
<p>I feel like this simple solution should work, but I'm getting invalid syntax errors:</p>
<pre><code>this.props.people.map(person => { value: person.id, text: person.name })
</code></pre>
| 0debug
|
monitor_read_memory (bfd_vma memaddr, bfd_byte *myaddr, int length,
struct disassemble_info *info)
{
CPUDebug *s = container_of(info, CPUDebug, info);
if (monitor_disas_is_physical) {
cpu_physical_memory_read(memaddr, myaddr, length);
} else {
cpu_memory_rw_debug(s->cpu, memaddr, myaddr, length, 0);
}
return 0;
}
| 1threat
|
Outlook 2010 Save .msg as Attachment Name VBA Macro : I hope you can help me. I am new to Outlook 2010 VBA, but need a macro to :-
Save a group of highlighted e-mails :-
a) As .msg files;
b) In a given folder;
c) Where the name of each is the attachment name.
To give you an example, say there are 20 e-mails in my sent items folder, I want to highlight 10 of them and run this macro, winding-up with 10 flat files in a given folder which bear the name of the attachment for each e-mail.
Every e-mail subjected to this macro *will* have just one attachment, so to be crystal-clear, if we have an e-mail with a subject line "Random Text goes here doesn't matter what", and an attachment "GO.XLSX", I want the extracted file to be called GO.msg and, to confirm, this is Outlook 2010 I am running.
I have looked through loads of VBA sites and macro snippets, but I am getting nowhere =[
Thank you so much for any help you can give me !!
| 0debug
|
Angular2 @Input from async pipe - availability in ngOnInit : <p>On one blog I've read that: </p>
<blockquote>
<p>The ngOnInit lifecycle hook is a guarantee that your bindings are
readily available.</p>
</blockquote>
<p>Is it true also with parameters passed using async pipe? For example:</p>
<pre><code><myComponent [myInput]="myObservableVariable | async">
...
</myComponent>
</code></pre>
<p>Will component wait for the variable to be resolved before starting up ngOnInit? </p>
<p>That would mean that sometimes, when data will take a while to resolve, component loading could take a long time.</p>
| 0debug
|
React-Redux mapStateToProps vs passing down parent props : <p>This may come off as a bit of a naive question, but I am new to react-redux and I'm learning as I go.</p>
<p><strong>Context:</strong> Given that I have a react-redux application. In my <strong><em>top-level</em></strong> component I have this at the bottom:</p>
<pre><code>function mapStateToProps({ auth }) {
return { auth };
}
export default connect(mapStateToProps)(newComponent);
</code></pre>
<p>The 'auth' portion comes from my reducer index.js file:</p>
<pre><code>import { combineReducers } from "redux";
import authReducer from "./authReducer";
export default combineReducers({
auth: authReducer
});
</code></pre>
<p>So now this component has access to all the data that comes with auth, which in my application contains all the user information needed.</p>
<p>As my application got bigger I realized I needed the data from the authReducer in other components that were 1 or 2 layers down from the top-level component</p>
<p><strong>My question(s) are</strong>: Is it better practice to connect the top-level component with the auth reducer, and pass down the necessary information to child components? What if a child 100-layers down needed information from the authReducer, would we still pass it down layer by layer? </p>
<p>OR would we just connect the authReducer as I did above to each component that needs it? Would that be expensive to do repeatedly? </p>
| 0debug
|
How to move jenkins job to sub folder? : <p>I have 10 jenkins job in folder <code>foo</code>. I have created a new sub folder <code>baar</code> in folder <code>foo</code>. How to move the 10 jobs from folder <code>foo</code> to the subfolder <code>baar</code>?</p>
| 0debug
|
Spring tags instead java code : I'm looking for good example, how can I replace this java code with spring tags.
<%
Object user = (String) request.getSession().getAttribute("User");
Object role = (String) request.getSession().getAttribute("role");
if(user == null){
out.println("<a href=\"register.jsp\">Register</a> <a href=\"login.jsp\">Login</a>");
} else {
out.println(" Hello " + user +" "+"<a href=\"LogoutServlet\" >Logout</a>");
}
%>
</div>
<div class="menu">
<%
if (role != null){
if(role.equals("admin")) out.println("<a href=\"adminPanel.jsp\">Admin Panel</a></br>");
out.println("<a href=\"userOrders\">Orders</a></br>");
} else {
if(user != null) out.println("<a href=\"userOrders\">Orders</a></br></br>");
}%>
| 0debug
|
document.location = 'http://evil.com?username=' + user_input;
| 1threat
|
void *address_space_map(AddressSpace *as,
hwaddr addr,
hwaddr *plen,
bool is_write)
{
hwaddr len = *plen;
hwaddr done = 0;
hwaddr l, xlat, base;
MemoryRegion *mr, *this_mr;
ram_addr_t raddr;
if (len == 0) {
return NULL;
}
l = len;
mr = address_space_translate(as, addr, &xlat, &l, is_write);
if (!memory_access_is_direct(mr, is_write)) {
if (bounce.buffer) {
return NULL;
}
l = MIN(l, TARGET_PAGE_SIZE);
bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
bounce.addr = addr;
bounce.len = l;
memory_region_ref(mr);
bounce.mr = mr;
if (!is_write) {
address_space_read(as, addr, bounce.buffer, l);
}
*plen = l;
return bounce.buffer;
}
base = xlat;
raddr = memory_region_get_ram_addr(mr);
for (;;) {
len -= l;
addr += l;
done += l;
if (len == 0) {
break;
}
l = len;
this_mr = address_space_translate(as, addr, &xlat, &l, is_write);
if (this_mr != mr || xlat != base + done) {
break;
}
}
memory_region_ref(mr);
*plen = done;
return qemu_ram_ptr_length(raddr + base, plen);
}
| 1threat
|
How to correct dotnet restore warning NU1604, does not contain an inclusive lower bound? : <p>While performing a <code>dotnet restore</code> on a .NET Core project (targeting .netcoreapp2.0.), I get the following warning: </p>
<blockquote>
<p>warning NU1604: Project dependency System.Net.NameResolution does not contain an inclusive lower bound. Include a lower bound in the dependency version to ensure consistent restore results.</p>
</blockquote>
<p>Here is the relevant line from the project file:</p>
<pre><code><PackageReference Include="System.Net.NameResolution" Verison="4.3.0" />
</code></pre>
<p>(If you are wondering, I have included that reference to avoid a warning NU1605: Detected package downgrade.)</p>
<p>How does one "include a lower bound in the dependency version to ensure consistent restore results"?</p>
| 0debug
|
Angular2: How to use pdfmake library : <p>Trying to use client-side pdf library <a href="https://github.com/bpampuch/pdfmake" rel="noreferrer">pdfmake</a> in my Angular 2 (version=4.2.x) project.</p>
<p>In .angular-cli.json file, I declared js like this:</p>
<pre><code>"scripts": [
"../node_modules/pdfmake/build/pdfmake.js",
"../node_modules/pdfmake/build/vfs_fonts.js"
]
</code></pre>
<p>And then in app.component.ts, I used it like this:</p>
<pre><code>import * as pdfMake from 'pdfmake';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
pdf: any;
downloadPdf() {
let item = {firstName: 'Peter', lastName: 'Parker'};
this.pdf = pdfMake;
this.pdf.createPdf(buildPdf(item)).open();
}
}
function buildPdf(value) {
var pdfContent = value;
var docDefinition = {
content: [{
text: 'My name is: ' + pdfContent.firstName + ' ' + pdfContent.lastName + '.'
}]
}
console.log(pdfContent);
return docDefinition;
}
</code></pre>
<p>I hit below error in browser console when loading the app:</p>
<pre><code>Uncaught TypeError: fs.readFileSync is not a function
at Object.<anonymous> (linebreaker.js:15)
at Object.<anonymous> (linebreaker.js:161)
at Object.../../../../linebreak/src/linebreaker.js (linebreaker.js:161)
at __webpack_require__ (bootstrap b937441…:54)
at Object.../../../../pdfmake/src/textTools.js (textTools.js:4)
at __webpack_require__ (bootstrap b937441…:54)
at Object.../../../../pdfmake/src/docMeasure.js (docMeasure.js:4)
at __webpack_require__ (bootstrap b937441…:54)
at Object.../../../../pdfmake/src/layoutBuilder.js (layoutBuilder.js:7)
at __webpack_require__ (bootstrap b937441…:54)
</code></pre>
<p>My workaround for solving this problem is: </p>
<p>Copy pdfmake.js and vfs_fonts.js to assets folder, and then add this to index.html:</p>
<pre><code><script src='assets/pdfmake.min.js'></script>
<script src='assets/vfs_fonts.js'></script>
</code></pre>
<p>Remove this from app.component.ts</p>
<pre><code>import * as pdfMake from 'pdfmake';
</code></pre>
<p>And add this to app.component.ts:</p>
<pre><code>declare var pdfMake: any;
</code></pre>
<p>Finally remove this from .angular-cli.js:</p>
<pre><code>"../node_modules/pdfmake/build/pdfmake.js",
"../node_modules/pdfmake/build/vfs_fonts.js"
</code></pre>
<p>It works but it's still a workaround.</p>
<p>Anyone knows how to use this library in Angular/Typscript way?</p>
<p>Thanks a lot!</p>
| 0debug
|
Is there a particular sequence in this row of numbers? : <p>I need to create a list with 14 elements, for each element the input integer must be 1,2,5,10,20,50,100 and then reversed. It would be silly to write int a = 1, b = 2, ....
So is there a way to loop this?
For instance, if I'd make a for loop, how could i make a connection between the required value and "i"?</p>
| 0debug
|
What is the "kube-system" namespace for? : <p>In a default openshift install, there is an unused project titled <code>kube-system</code>. It seems like <code>openshift-infra</code> is for things like metrics, <code>default</code> is for the router and registry, and <code>openshift</code> is for global templates. </p>
<p>What is the <code>kube-system</code> project used for though? I can't find any docs on it.</p>
| 0debug
|
static int64_t update_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
{
MpegMuxContext *s = ctx->priv_data;
int64_t scr;
if (s->is_vcd)
scr = 36000 + s->packet_number * 1200;
else {
if (stream_index == s->scr_stream_index
&& pts != AV_NOPTS_VALUE)
scr = pts;
else
scr = s->last_scr;
}
s->last_scr=scr;
return scr;
}
| 1threat
|
Sum all the digits of a number Javascript : <p>I am newbie.</p>
<p>I want to make small app which will calculate the sum of all the digits of a number.</p>
<p>For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .</p>
<p>Please help me</p>
| 0debug
|
static void pc_compat_2_0(MachineState *machine)
{
pc_compat_2_1(machine);
smbios_legacy_mode = true;
has_reserved_memory = false;
pc_set_legacy_acpi_data_size();
}
| 1threat
|
static int decode(MimicContext *ctx, int quality, int num_coeffs,
int is_iframe)
{
int y, x, plane, cur_row = 0;
for(plane = 0; plane < 3; plane++) {
const int is_chroma = !!plane;
const int qscale = av_clip(10000-quality,is_chroma?1000:2000,10000)<<2;
const int stride = ctx->flipped_ptrs[ctx->cur_index].linesize[plane];
const uint8_t *src = ctx->flipped_ptrs[ctx->prev_index].data[plane];
uint8_t *dst = ctx->flipped_ptrs[ctx->cur_index ].data[plane];
for(y = 0; y < ctx->num_vblocks[plane]; y++) {
for(x = 0; x < ctx->num_hblocks[plane]; x++) {
if(is_iframe || get_bits1(&ctx->gb) == is_chroma) {
if(is_chroma || is_iframe || !get_bits1(&ctx->gb)) {
if(!vlc_decode_block(ctx, num_coeffs, qscale))
return 0;
ctx->dsp.idct_put(dst, stride, ctx->dct_block);
} else {
unsigned int backref = get_bits(&ctx->gb, 4);
int index = (ctx->cur_index+backref)&15;
uint8_t *p = ctx->flipped_ptrs[index].data[0];
ff_thread_await_progress(&ctx->buf_ptrs[index], cur_row, 0);
if(p) {
p += src -
ctx->flipped_ptrs[ctx->prev_index].data[plane];
ctx->dsp.put_pixels_tab[1][0](dst, p, stride, 8);
} else {
av_log(ctx->avctx, AV_LOG_ERROR,
"No such backreference! Buggy sample.\n");
}
}
} else {
ff_thread_await_progress(&ctx->buf_ptrs[ctx->prev_index], cur_row, 0);
ctx->dsp.put_pixels_tab[1][0](dst, src, stride, 8);
}
src += 8;
dst += 8;
}
src += (stride - ctx->num_hblocks[plane])<<3;
dst += (stride - ctx->num_hblocks[plane])<<3;
ff_thread_report_progress(&ctx->buf_ptrs[ctx->cur_index], cur_row++, 0);
}
}
return 1;
}
| 1threat
|
recieving error "Out of memory. The likely cause is an infinite recursion within the program." in MatLab : <p>I am trying to implement quick sort in MatLab. I have two functions, one which splits a given list into two smaller lists, one greater and one smaller than the pivot. The second function recursively calls the quick sort and iterates to the next smaller list, calling quick sort again. My code is below. When I go to run the code with my list of 300 randomly generated numbers, I get the error "Out of memory. The likely cause is an infinite recursion within the program.".</p>
<pre><code>function [ less, pivot, greater ] = SplitList( list, pivotindex )
%List Splitting Function
%In order to preform quick sort you firts must be able to split the list
%into two, one which is greater than, and one which is less than the pivot.
pivot = list(1,pivotindex);
greater = [];
less = [];
for l = 1:length(list)
if list(1,l) > pivot
greater = [greater list(1, l)];
else if list(1,l) <= pivot
less = [less list(1, l)];
end
end
end
end
function [ qs_list ] = quick_sort( list )
%Recursive Quick Sort
% quick sort algorithm to sort a list of numbers
%set (0,'RecursionLimit',1000);
pivotindex = round(length(list)/2); %sets pivot at the median value of the array
if length(list) > 1
[ less, pivot, greater ] = SplitList( list, pivotindex ); %calls the SplitList function
qs_list = [quick_sort(less) pivot quick_sort(greater)]; %calls quick_sort within the function
else
qs_list = list;
end
end
</code></pre>
| 0debug
|
static inline void RENAME(yvu9toyv12)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc,
uint8_t *ydst, uint8_t *udst, uint8_t *vdst,
unsigned int width, unsigned int height, int lumStride, int chromStride)
{
memcpy(ydst, ysrc, width*height);
}
| 1threat
|
C# How to divide a number by another and get the result in the format hh:mm:ss:<remainder> : I want the value of division by the following format:
hh:mm:ss:ff
where ff is the reminder
eg:
63 divide by 25
00:00:02:13
How to achieve this?
Thanks
| 0debug
|
static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip)
{
target_ulong pc = s->cs_base + eip;
if (use_goto_tb(s, pc)) {
tcg_gen_goto_tb(tb_num);
gen_jmp_im(eip);
tcg_gen_exit_tb((uintptr_t)s->tb + tb_num);
} else {
gen_jmp_im(eip);
gen_eob(s);
}
}
| 1threat
|
ViewDragHelper - Child layout changes ignored while dragging : <p>I'm trying to apply margin updates or animations to a child view which parent is dragged using a <code>ViewDragHelper</code>.</p>
<p>However the updated layout properties have no effect and are not rendered while the view is dragged. Everything from adding and removing views, to layout animations or layout param updates are ignored while dragging:</p>
<p>To illustrate this issue, i've created a delayed runnable which updates the height of a view (the green view) after 3 seconds:</p>
<pre><code>spacer.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG,"set layout params!!!!");
ViewGroup.LayoutParams spacerParams = spacer.getLayoutParams();
spacerParams.height = (int) (200+(Math.random()*200));
spacer.setLayoutParams(spacerParams);
}
},3000);
</code></pre>
<p>Check this demo screen recording:
<a href="http://imgur.com/a/dDiGt">http://imgur.com/a/dDiGt</a></p>
| 0debug
|
What is the difference between updated hook and watchers in VueJS? : <p>I'm discovering VueJS and I don't understand exactly the differences between <code>updated</code> and watchers.</p>
<h2>Updated hook</h2>
<p>It is a lifecycle hook. According to <a href="https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram" rel="noreferrer">the official documentation</a>, it is triggered whenever data changes. So whenever a <code>prop</code> or a <code>data</code> is updated (the value, not only the pointer), <code>updated</code> is called.</p>
<h2>Watchers</h2>
<p>In the documentation, watchers are compared to computed properties. But in which cases would it be best to use updated instead of watchers ?</p>
<p>It seems that in both cases, DOM is not updated when the callback is called (<code>nextTick()</code> is required if we want to manipulate the changes in the DOM). The only difference I see is that <code>watchers</code> are only triggered when one precise property (or data) is updated where <code>updated</code> is always called.</p>
<p>I can't figure out what are the pros of updating whenever a data changes (<code>updating</code>) if we can be more accurate (<code>watchers</code>).</p>
<p>Here are my thoughts.</p>
<p>Thanks :)</p>
| 0debug
|
PHP Using RegEx to get #string from text to array : i'm looking for php code to split word from text using regex or other way.
$textstring="one #two three #four #five";
i need to get #two,#four,#five save into array.
thx,
kew
| 0debug
|
test_tls_get_ipaddr(const char *addrstr,
char **data,
int *datalen)
{
struct addrinfo *res;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
g_assert(getaddrinfo(addrstr, NULL, &hints, &res) == 0);
*datalen = res->ai_addrlen;
*data = g_new(char, *datalen);
memcpy(*data, res->ai_addr, *datalen);
}
| 1threat
|
static void bt_hid_interrupt_sdu(void *opaque, const uint8_t *data, int len)
{
struct bt_hid_device_s *hid = opaque;
if (len > BT_HID_MTU || len < 1)
goto bad;
if ((data[0] & 3) != BT_DATA_OUTPUT)
goto bad;
if ((data[0] >> 4) == BT_DATA) {
if (hid->intr_state)
goto bad;
hid->data_type = BT_DATA_OUTPUT;
hid->intrdataout.len = 0;
} else if ((data[0] >> 4) == BT_DATC) {
if (!hid->intr_state)
goto bad;
} else
goto bad;
memcpy(hid->intrdataout.buffer + hid->intrdataout.len, data + 1, len - 1);
hid->intrdataout.len += len - 1;
hid->intr_state = (len == BT_HID_MTU);
if (!hid->intr_state) {
memcpy(hid->dataout.buffer, hid->intrdataout.buffer,
hid->dataout.len = hid->intrdataout.len);
bt_hid_out(hid);
}
return;
bad:
fprintf(stderr, "%s: bad transaction on Interrupt channel.\n",
__func__);
}
| 1threat
|
How to make a full screen dialog in flutter? : <p>I want to make a full screen dialog box. Dialog box background must be opaque.
Here is an example:
<a href="https://i.stack.imgur.com/U5W5i.png" rel="noreferrer"><img src="https://i.stack.imgur.com/U5W5i.png" alt="enter image description here"></a></p>
<p>How to make like this in Flutter?</p>
| 0debug
|
How to restore auto_ptr in Visual Studio C++17 : <p>This blog page mentions that Visual Studio removes some std features:</p>
<p><a href="https://blogs.msdn.microsoft.com/vcblog/2017/12/08/c17-feature-removals-and-deprecations/" rel="noreferrer">https://blogs.msdn.microsoft.com/vcblog/2017/12/08/c17-feature-removals-and-deprecations/</a></p>
<p>I have a project that consumes some C++ libraries that now use C++17 features. The project also consumes a third party library websocketpp (<a href="https://github.com/zaphoyd/websocketpp" rel="noreferrer">https://github.com/zaphoyd/websocketpp</a>) that still uses some now removed features. eg auto_ptr and binary_function. I'm getting compiler errors that they are not a member of 'std'.</p>
<p>The blog above mentions that removed features can be restored using a fine grain control. I'm thinking I could use that to get this project to compile for now. Longer term I will see about upgrading websocketpp to C++17 or replacing it with something else.</p>
<p>But, what is the magic to restore features? Is there something I need to #define? If so, what?</p>
| 0debug
|
Is accessing async .Result considered as bad practice? : <p>If I have following</p>
<pre><code> public async Task<Owner> Get(int carId)
{
var car = await myDbContext.Cars.FindAsync(carId);
return car.Owner;
}
</code></pre>
<p>I cannot access the Owner property in the first line cause it's a async call.</p>
<p>If I access it using await <code>myDbContext.Cars.FindAsync(carId).Result.Owner</code> does that mean that I'll get stuck in a deadlock sometime or does it have some other side effects?</p>
| 0debug
|
artificial intelligent, prolog, ai, gprolog : no smoke without fire.
identify conclusion and condition from above statement for make prolog program.
in the answer, the conclusion is fire and condition is smoke.
but I don't how?
another possible answer, the conclusion is smoke and condition is fire.
please explain answer and which is possible from this two and how.
| 0debug
|
How to implement full calendar using angular js : <p>I want to add a event calender which is same like Full calender.How to implement angular fullcalendar in my app?.</p>
| 0debug
|
how to save data in database : please refer code below. im using phpMyAdmin to store my data n xampp(as my server). i found this code and add into my website. my question is, how to save the result in database. anyone??
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geoip-db.com</title>
</head>
<body>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Postal: <span id="postal"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP address: <span id="ipv4"></span></div>
</body>
<script>
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = document.getElementById('city');
var postal = document.getElementById('postal');
var latitude = document.getElementById('latitude');
var longitude = document.getElementById('longitude');
var ip = document.getElementById('ipv4');
function callback(data)
{
country.innerHTML = data.country_name;
state.innerHTML = data.state;
city.innerHTML = data.city;
postal.innerHTML = data.postal;
latitude.innerHTML = data.latitude;
longitude.innerHTML = data.longitude;
ip.innerHTML = data.IPv4;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://geoip-db.com/json/geoip.php?jsonp=callback';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(script, h);
</script>
</html>
<!-- end snippet -->
| 0debug
|
how can I simplify my if-else statement in java? : In my code I have a method `size(MyData)` that returns size of data - it can be 0 or greater.
I also have a flag `exclude` that can be `true` or `false`. The point of my algorithm is to do some operation on data based on its size and the value of the flag.
- If the size is greater than 0, I want to do operation on data.
- If the size is 0, then I need to check the value of the flag `excluded`. In that case, if the flag `excluded` is set to true, I don't want to do operation on data. But if the flag is set to false, I need to do operation on data.
This is my algorithm so far:
int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0) {
//do operation
}
else {
if (!exclude) {
//do operation
}
}
is there a better way of writing this algorithm?
Thanks!
| 0debug
|
How to make the horizontal row images move up? : Im trying to move my horizontal row of images upa few pixels. How do I go about this? I'm a newbie.
| 0debug
|
static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
int64_t sector_num, uint8_t *buf, int nb_sectors,
BlockDriverCompletionFunc *cb, void *opaque)
{
BDRVRawState *s = bs->opaque;
RawAIOCB *acb;
if (fd_open(bs) < 0)
return NULL;
acb = qemu_aio_get(bs, cb, opaque);
if (!acb)
return NULL;
acb->fd = raw_fd_pool_get(s);
acb->aiocb.aio_fildes = acb->fd;
acb->aiocb.aio_sigevent.sigev_signo = SIGUSR2;
acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
acb->aiocb.aio_buf = buf;
if (nb_sectors < 0)
acb->aiocb.aio_nbytes = -nb_sectors;
else
acb->aiocb.aio_nbytes = nb_sectors * 512;
acb->aiocb.aio_offset = sector_num * 512;
acb->next = posix_aio_state->first_aio;
posix_aio_state->first_aio = acb;
return acb;
}
| 1threat
|
C# (.NET), Html parse using regex : <p>Using Regex, I'm trying to get data from html code, but I don't know how build it, without using any html tags.<br>
I have some string (<strong>item-desc</strong>), and count of symbols after this string, which must be my data.<br>
Something like: in <strong>item-desc12345abcde</strong>, I'm using regex with value of 6 symbols, and i got <strong>12345a</strong>.
This expression give me only 1 symbol after my string: </p>
<pre><code>Regex itemInfoFilter = new Regex(@"item-desc\s*(.+?)\s*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
</code></pre>
| 0debug
|
Ambiguity in parameter type inference for C# lambda expressions : <p>My question is motivated by Eric Lippert's <a href="https://blogs.msdn.microsoft.com/ericlippert/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five/">this blog post</a>. Consider the following code:</p>
<pre><code>using System;
class Program {
class A {}
class B {}
static void M(A x, B y) { Console.WriteLine("M(A, B)"); }
static void Call(Action<A> f) { f(new A()); }
static void Call(Action<B> f) { f(new B()); }
static void Main() { Call(x => Call(y => M(x, y))); }
}
</code></pre>
<p>This compiles successfully and prints <code>M(A, B)</code>, because the compiler figures out that the types of <code>x</code> and <code>y</code> in the lambda expressions should be <code>A</code> and <code>B</code> respectively. Now, add an overload for <code>Program.M</code>:</p>
<pre><code>using System;
class Program {
class A {}
class B {}
static void M(A x, B y) { Console.WriteLine("M(A, B)"); }
static void M(B x, A y) { Console.WriteLine("M(B, A)"); } // added line
static void Call(Action<A> f) { f(new A()); }
static void Call(Action<B> f) { f(new B()); }
static void Main() { Call(x => Call(y => M(x, y))); }
}
</code></pre>
<p>This yields a compile-time error:</p>
<blockquote>
<p>error CS0121: The call is ambiguous between the following methods or properties: 'Program.Call(Action<Program.A>)' and 'Program.Call(Action<Program.B>)'</p>
</blockquote>
<p>The compiler cannot infer the types of <code>x</code> and <code>y</code>. It may be that <code>x</code> is of type <code>A</code> and <code>y</code> is of type <code>B</code> or vice versa, and neither can be preferred because of full symmetry. So far so good. Now, add one more overload for <code>Program.M</code>:</p>
<pre><code>using System;
class Program {
class A {}
class B {}
static void M(A x, B y) { Console.WriteLine("M(A, B)"); }
static void M(B x, A y) { Console.WriteLine("M(B, A)"); }
static void M(B x, B y) { Console.WriteLine("M(B, B)"); } // added line
static void Call(Action<A> f) { f(new A()); }
static void Call(Action<B> f) { f(new B()); }
static void Main() { Call(x => Call(y => M(x, y))); }
}
</code></pre>
<p>This compiles successfully and prints <code>M(A, B)</code> again! I can guess the reason. The compiler resolves the overload of <code>Program.Call</code> trying to compile the lambda expression <code>x => Call(y => M(x, y))</code> for <code>x</code> of type <code>A</code> and for <code>x</code> of type <code>B</code>. The former succeeds, while the latter fails because of ambiguity detected when trying to infer the type of <code>y</code>. Therefore, the compiler concludes that <code>x</code> must be of type <code>A</code>.</p>
<p>Thus <em>adding more ambiguity results in less ambiguity</em>. This is weird. Moreover, this is inconsistent with what Eric wrote in the above-mentioned post:</p>
<blockquote>
<p>If it has more than one solution then compilation fails with an ambiguity error.</p>
</blockquote>
<p>Is there any good reason for the current behavior? Is it just the matter of making the compiler's life easier? Or is it rather a flaw in the compiler/specification?</p>
| 0debug
|
def count_Odd_Squares(n,m):
return int(m**0.5) - int((n-1)**0.5)
| 0debug
|
SELECTING with multiple WHERE conditions on same column from sqlserver : I want to pic values from same column using and clause query is something like this.
select * from degree_detail_result where course_id=1 and course_id=2 and course_id=3
tell me the solution of above query.
| 0debug
|
a function with too many parameters in perl : <p>I have a function has too many parameters. I have viewed the resolving approach in PHP that passing class object into the function instead of many parameters. Is it any approaches for perl?</p>
<p>Thanks</p>
| 0debug
|
static int aac_decode_frame(AVCodecContext *avccontext, void *data,
int *data_size, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
AACContext *ac = avccontext->priv_data;
ChannelElement *che = NULL, *che_prev = NULL;
GetBitContext gb;
enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;
int err, elem_id, data_size_tmp;
int buf_consumed;
int samples = 1024, multiplier;
int buf_offset;
init_get_bits(&gb, buf, buf_size * 8);
if (show_bits(&gb, 12) == 0xfff) {
if (parse_adts_frame_header(ac, &gb) < 0) {
av_log(avccontext, AV_LOG_ERROR, "Error decoding AAC frame header.\n");
return -1;
}
if (ac->m4ac.sampling_index > 12) {
av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);
return -1;
}
}
while ((elem_type = get_bits(&gb, 3)) != TYPE_END) {
elem_id = get_bits(&gb, 4);
if (elem_type < TYPE_DSE && !(che=get_che(ac, elem_type, elem_id))) {
av_log(ac->avccontext, AV_LOG_ERROR, "channel element %d.%d is not allocated\n", elem_type, elem_id);
return -1;
}
switch (elem_type) {
case TYPE_SCE:
err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
break;
case TYPE_CPE:
err = decode_cpe(ac, &gb, che);
break;
case TYPE_CCE:
err = decode_cce(ac, &gb, che);
break;
case TYPE_LFE:
err = decode_ics(ac, &che->ch[0], &gb, 0, 0);
break;
case TYPE_DSE:
err = skip_data_stream_element(ac, &gb);
break;
case TYPE_PCE: {
enum ChannelPosition new_che_pos[4][MAX_ELEM_ID];
memset(new_che_pos, 0, 4 * MAX_ELEM_ID * sizeof(new_che_pos[0][0]));
if ((err = decode_pce(ac, new_che_pos, &gb)))
break;
if (ac->output_configured > OC_TRIAL_PCE)
av_log(avccontext, AV_LOG_ERROR,
"Not evaluating a further program_config_element as this construct is dubious at best.\n");
else
err = output_configure(ac, ac->che_pos, new_che_pos, 0, OC_TRIAL_PCE);
break;
}
case TYPE_FIL:
if (elem_id == 15)
elem_id += get_bits(&gb, 8) - 1;
if (get_bits_left(&gb) < 8 * elem_id) {
av_log(avccontext, AV_LOG_ERROR, overread_err);
return -1;
}
while (elem_id > 0)
elem_id -= decode_extension_payload(ac, &gb, elem_id, che_prev, elem_type_prev);
err = 0;
break;
default:
err = -1;
break;
}
che_prev = che;
elem_type_prev = elem_type;
if (err)
return err;
if (get_bits_left(&gb) < 3) {
av_log(avccontext, AV_LOG_ERROR, overread_err);
return -1;
}
}
spectral_to_sample(ac);
multiplier = (ac->m4ac.sbr == 1) ? ac->m4ac.ext_sample_rate > ac->m4ac.sample_rate : 0;
samples <<= multiplier;
if (ac->output_configured < OC_LOCKED) {
avccontext->sample_rate = ac->m4ac.sample_rate << multiplier;
avccontext->frame_size = samples;
}
data_size_tmp = samples * avccontext->channels * sizeof(int16_t);
if (*data_size < data_size_tmp) {
av_log(avccontext, AV_LOG_ERROR,
"Output buffer too small (%d) or trying to output too many samples (%d) for this frame.\n",
*data_size, data_size_tmp);
return -1;
}
*data_size = data_size_tmp;
ac->dsp.float_to_int16_interleave(data, (const float **)ac->output_data, samples, avccontext->channels);
if (ac->output_configured)
ac->output_configured = OC_LOCKED;
buf_consumed = (get_bits_count(&gb) + 7) >> 3;
for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
if (buf[buf_offset])
break;
return buf_size > buf_offset ? buf_consumed : buf_size;
}
| 1threat
|
infoWindow in google maps on multiple markers : <p>i've created a google maps, which retrieve data from a csv file. This seem to work fine, however when i loop through all the objects the infoWindow does not seem to work. i guess this is due to the fact that the <code>marker</code> variable is inside a for loop. i've tried to move the code to inside the loop, however this result in the infoWindow placed randomly on the map instead above the clicked marker. How can i achieve the infoWindow to work with multiple markers?</p>
<p><strong>db.csv example</strong></p>
<pre><code>40.740;-74.18;test;haha;
40.740;-74.20;test;haha;
</code></pre>
<p><strong>html & java</strong></p>
<pre><code><head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="normalize.css">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer">
<div id="map"></div>
</div>
<div id="abc">
<div id="popupContact">
<section class="register">
<h1>CAMP INFORMATIONER:</h1>
<form method="post" action="index.html">
<div class="reg_section personal_info">
<input type="text" name="username" value="" placeholder="Campnavn">
<textarea name="textarea" id="description" placeholder="Beskrivelse"></textarea>
</div>
<div>
<span class="submit" style="text-align: left; padding: 0 10px;"><input TYPE="button"name="commit" value="Tilføj" onclick="placeMarker(currentMarker, document.getElementById('description'));"></span>
<span class="submit" style="text-align: right; padding: 0 10px;"><input TYPE="button" name="commit" value="Fortryd" onclick="div_hide();"></span>
</div>
</form>
</section>
</div>
</div>
</div>
<script>
var mapCanvas;
var currentMarker;
function initialize() {
var myOptions = {
center: {lat: 40.740, lng: -74.18},
zoom : 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapCanvas = new google.maps.Map(document.getElementById("mapContainer"), myOptions);
var returnValue = "";
var request = new XMLHttpRequest();
// Read the lat/long info for markers
request.open("GET", "db.csv", false);
request.send(null);
returnValue = request.responseText;
// Convert our data from the CVS file to a usable array
var data = CSVToArray(returnValue);
for (var i = 0; i < data.length; i++)
{
// Create a lat/long object readable by Google
var myLatlng = new google.maps.LatLng(parseFloat(data[i][0]), parseFloat(data[i][1]));
// Generate a marker from the lat/long object and add it to the map
var marker = new google.maps.Marker({
position: myLatlng,
map: mapCanvas,
title: data[i][2],
description: data[i][3]
});
}
var imageBounds = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655
};
historicalOverlay = new google.maps.GroundOverlay(
'http://i.stack.imgur.com/0mgx2.jpg',
imageBounds);
historicalOverlay.setMap(mapCanvas);
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(historicalOverlay, 'click', function(e) {
console.log("clicked'");
currentMarker = e.latLng;
infowindow.close();
div_show();
});
//Changes zoom levels when the projection is available.
google.maps.event.addListenerOnce(mapCanvas, "projection_changed", function(){
mapCanvas.setMapTypeId(google.maps.MapTypeId.HYBRID); //Changes the MapTypeId in short time.
setZoomLimit(mapCanvas, google.maps.MapTypeId.ROADMAP);
setZoomLimit(mapCanvas, google.maps.MapTypeId.HYBRID);
setZoomLimit(mapCanvas, google.maps.MapTypeId.SATELLITE);
setZoomLimit(mapCanvas, google.maps.MapTypeId.TERRAIN);
mapCanvas.setMapTypeId(google.maps.MapTypeId.ROADMAP); //Sets the MapTypeId to original.
});
// InfoWindow content
var content = '<div id="iw-container">' +
'<div class="iw-title">title</div>' +
'<div class="iw-content">' +
'<p>Founded in 1824, the Porcelain Factory of Vista Alegre was the first industrial unit dedicated to porcelain production in Portugal. For the foundation and success of this risky industrial development was crucial the spirit of persistence of its founder, José Ferreira Pinto Basto. Leading figure in Portuguese society of the nineteenth century farm owner, daring dealer, wisely incorporated the liberal ideas of the century, having become "the first example of free enterprise" in Portugal.</p>' +
'</div>' +
'<div class="iw-bottom-gradient"></div>' +
'</div>';
// A new Info Window is created and set content
var infowindow = new google.maps.InfoWindow({
content: content,
// Assign a maximum value for the width of the infowindow allows
// greater control over the various content elements
maxWidth: 350
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(mapCanvas, marker);
//title
document.getElementById("iw-title").innerHTML = marker.title;
//description
document.getElementById("iw-content p").innerHTML = marker.description;
});
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(mapCanvas, 'click', function() {
infowindow.close();
});
google.maps.event.addListener(infowindow, 'domready', function() {
// Reference to the DIV that wraps the bottom of infowindow
var iwOuter = $('.gm-style-iw');
/* Since this div is in a position prior to .gm-div style-iw.
* We use jQuery and create a iwBackground variable,
* and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
*/
var iwBackground = iwOuter.prev();
// Removes background shadow DIV
iwBackground.children(':nth-child(2)').css({'display' : 'none'});
// Removes white background DIV
iwBackground.children(':nth-child(4)').css({'display' : 'none'});
// Moves the infowindow 115px to the right.
iwOuter.parent().parent().css({left: '115px'});
// Moves the shadow of the arrow 76px to the left margin.
iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Moves the arrow 76px to the left margin.
iwBackground.children(':nth-child(3)').attr('style', function(i,s){ return s + 'left: 76px !important;'});
// Changes the desired tail shadow color.
iwBackground.children(':nth-child(3)').find('div').children().css({'z-index' : '1'});
// Reference to the div that groups the close button elements.
var iwCloseBtn = iwOuter.next();
// Apply the desired effect to the close button
iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #fff', 'border-radius': '13px', 'box-shadow': '0 0 5px #7D0F33'});
// If the content of infowindow not exceed the set maximum height, then the gradient is removed.
if($('.iw-content').height() < 140){
$('.iw-bottom-gradient').css({display: 'none'});
}
// The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
iwCloseBtn.mouseout(function(){
$(this).css({opacity: '1'});
});
});
}
function div_show() {
$('#abc').fadeIn(400);
}
//Function to Hide Popup
function div_hide(){
$('#abc').fadeOut(400);
}
function placeMarker(location, label) {
var marker = new google.maps.Marker({
position: location,
map: mapCanvas,
labelContent : label
});
div_hide();
}
function setZoomLimit(map, mapTypeId){
//Gets MapTypeRegistry
var mapTypeRegistry = map.mapTypes;
//Gets the specified MapType
var mapType = mapTypeRegistry.get(mapTypeId);
//Sets limits to MapType
mapType.maxZoom = 15; //It doesn't work with SATELLITE and HYBRID maptypes.
mapType.minZoom = 15;
}
function CSVToArray(strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ";");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData ))
{
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter))
{
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else
{
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
<body>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>/* Author : iMomen
Website: www.iMomen.com
E-mail : Coder@iMomen.com
*/
#mapContainer {
height: 100%;
width: 100%;
margin-left: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-top: 0px;
position: relative;
}
#map {
height: 100%;
}
.gm-style-mtc {
display: none;
}
.gmnoprint {
display: none;
}
#abc {
width:100%;
height:100%;
top:0;
left:0;
display:none;
position:fixed;
background-color: rgba(0,0,0, .5);
overflow:auto;
}
div#popupContact {
width: 350px; /*can be in percentage also.*/
margin: 0;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
background-color: #ffffff;
}
div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
html, body {
height:100%;
width: 100%;
margin-left: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-top: 0px;
overflow:hidden;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
a {
color:#FF3679;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.container {
width: 350px;
margin-left: auto;
margin-right: auto;
}
.reg_section {
padding:0;
margin: 10px 0;
border-bottom: 1px dotted #eee;
}
.reg_section h3 {
font-size: 13px;
margin: 5px 0;
color: #C4A2A2;
}
/* Form */
.register {
text-align: center;
position: relative;
padding: 20px 20px 20px 20px;
background: #fff;
border-radius: 3px;
}
.register:before {
content: '';
position: absolute;
top: -8px;
right: -8px;
bottom: -8px;
left: -8px;
z-index: -1;
background:rgba(255, 173, 200, 0.08);
border-radius:7px;
-webkit-border-radius: 7px;
}
.register h1 {
margin: -20px -20px 0;
line-height: 40px;
font-size: 15px;
font-weight: bold;
color:#694551;
text-align: center;
border-bottom:1px solid #EDEDED;
border-radius: 3px 3px 0 0;
-webkit-box-shadow: 0 1px #f5f5f5;
-moz-box-shadow: 0 1px #f5f5f5;
box-shadow: 0 1px #f5f5f5;
}
.register input[type=text], .register input[type=password] ,.register select,.register textarea {
width: 278px;
}
.register p.terms {
float: left;
line-height: 31px;
}
.register p.terms label {
font-size: 12px;
color: #777;
cursor: pointer;
}
.register p.terms input {
position: relative;
bottom: 1px;
margin-right: 4px;
vertical-align: middle;
}
.register-help {
margin: 20px 0;
font-size: 11px;
text-align: center;
color:#FFFFFF;
}
.register-help a {
color:#FF3679;
text-shadow:0 1px #1E0E13;
}
:-moz-placeholder {
color: #404040 !important;
font-size: 13px;
}
::-webkit-input-placeholder {
color: #ccc;
font-size: 13px;
}
input {
font-family:"Trebuchet MS",tahoma;
font-size: 14px;
}
input[type=text], input[type=password] ,.register select,.register textarea {
margin: 5px;
padding: 0 10px;
height: 34px;
color: #404040;
background: #fff;
border-width: 1px;
border-style: solid;
border-color: #c4c4c4 #d1d1d1 #d4d4d4;
border-radius:3px;
--webkit-border-radius: 5px;
outline:3px solid rgba(200, 105, 137, 0.09);
-moz-outline-radius:7px;
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
-moz-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
margin:10px 0;
}
input[type=text]:focus, input[type=password]:focus{
border-color:#FFF7F9;
outline-color:rgba(254, 225, 235, 0.7);
outline-offset: 0;
}
input[type=button] {
padding:0 0px;
height: 29px;
width: 100px;
font-size: 12px;
font-weight: bold;
color:#FFFFFF;
text-shadow:0 1px #4D1124;
border-width: 1px;
border-style: solid;
border-color:#693647;
outline: none;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
background-color: #7D0F33;
}
input[type=button]:active {
background: #7D0F33;
-webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
-moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
line-height: 34px;
}
.register select {
padding:6px 10px;
width: 300px;
color: #777777;
}
.register textarea {
height: 50px;
padding: 10px;
color: #404040;
}
/* About */
.about {
margin:10px auto;
width: 300px;
text-align: center;
color:#EEA5BD;
font-size: 12px;
}
.about a {
padding: 1px 3px;
margin: 0 -1px;
color: #fff;
text-decoration: none;
text-shadow: 0 -1px rgba(0, 0, 0, 0.2);
border-radius: 2px;
}
.about a:hover {
color:#2F0916;
text-shadow: none;
background: #E83671;
}
.links {
zoom: 1;
}
.links:before, .links:after {
content: "";
display: table;
}
.links:after {
clear: both;
}
.links a {
padding: 6px 0;
float: left;
width: 50%;
font-size: 14px;
}
.gm-style-iw {
width: 350px !important;
top: 15px !important;
left: 0px !important;
background-color: #fff;
border-radius: 2px 2px 10px 10px;
}
#iw-container {
margin-bottom: 10px;
}
#iw-container .iw-title {
font-family: 'Open Sans Condensed', sans-serif;
font-size: 22px;
font-weight: 400;
padding: 10px;
background-color: #7D0F33;
color: white;
margin: 0;
border-radius: 2px 2px 0 0;
}
#iw-container .iw-content {
font-size: 13px;
line-height: 18px;
font-weight: 400;
margin-right: 1px;
padding: 15px 5px 20px 15px;
max-height: 140px;
overflow-y: auto;
overflow-x: hidden;
}
.iw-subTitle {
font-size: 16px;
font-weight: 700;
padding: 5px 0;
}
.iw-bottom-gradient {
position: absolute;
width: 326px;
height: 25px;
bottom: 10px;
right: 18px;
background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
}
</code></pre>
| 0debug
|
How to run gunicorn from a folder that is not the django project folder : <p>I git cloned a project in my home folder, let's call it <code>/home/telessaude</code>. So the project root is located at <code>/home/telessaude/telessaude_branch_master</code></p>
<p>If I am inside the Django project home folder ( /home/telessaude/telessaude_branch_master ) and issue a gunicorn comman such as</p>
<p><code>gunicorn -w 2 -b 0.0.0.0:8000 telessaude.wsgi_dev:application --reload --timeout 900</code></p>
<p>gunicorn starts and works just fine. However ... if I try to run the same command on one directory above ( /home/telessaude ), I get the following error:</p>
<pre><code>telessaude@ubuntu:~$ gunicorn -w 2 -b 0.0.0.0:8000 telessaude.wsgi_dev:application --reload --timeout 900
[2017-03-22 16:39:28 +0000] [10405] [INFO] Starting gunicorn 19.6.0
[2017-03-22 16:39:28 +0000] [10405] [INFO] Listening at: http://0.0.0.0:8000 (10405)
[2017-03-22 16:39:28 +0000] [10405] [INFO] Using worker: sync
[2017-03-22 16:39:28 +0000] [10410] [INFO] Booting worker with pid: 10410
[2017-03-22 16:39:28 +0000] [10410] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker
worker.init_process()
File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/usr/local/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi
self.wsgi = self.app.wsgi()
File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 357, in import_app
__import__(module)
ImportError: No module named telessaude.wsgi_dev
</code></pre>
<p>I also tried running gunicorn in my home folder with</p>
<p><code>gunicorn -w 2 -b 0.0.0.0:8000 telessaude_branch_master.telessaude.wsgi_dev:application --reload --timeout 900</code></p>
<p>and </p>
<p><code>gunicorn -w 2 -b 0.0.0.0:8000 /home/telessaude/telessaude_branch_master/telessaude.wsgi_dev:application --reload --timeout 900</code></p>
<p>but none of them also worked. Can someone tell me how to fix this? I need to run gunicorn from any folder, because I must add it as a "command" parameter to supervisor.</p>
<p>I'm not using a virtual enviromnment.</p>
| 0debug
|
How to revert a GitHub repo to a certain commit : <p>I've been committing changes inside my GitHub repo. I now want to roll back to a certain commit that I've made sometime ago.</p>
<p>How do I reset my repo so that all the commits I've made, after the one i'd like to go back to, are wiped?</p>
<p>I've found some answers regarding <code>git reset --hard <id></code> but it's not doing what I want.</p>
| 0debug
|
how to bring the vscode css color picker feature into js file with string that match color name format? : <p><a href="https://code.visualstudio.com/docs/languages/css" rel="noreferrer">https://code.visualstudio.com/docs/languages/css</a></p>
<p>None of the current plugin able to do so. I am really surprised. even intellij has this support!</p>
<p>Also the reply from vscode itself is a bit not helpful either.
<a href="https://github.com/Microsoft/vscode/issues/36485" rel="noreferrer">https://github.com/Microsoft/vscode/issues/36485</a></p>
<p>Any hint on how to build such plugin, seems shouldn't be really hard since its really just porting the feature from one file extension to another?</p>
<p>Anyone able to resolve this?</p>
| 0debug
|
How to fix Parse error: syntax error, unexpected 'else' (T_ELSE), expecting end of file : <p>This code provides this error Parse error: syntax error, unexpected 'else' (T_ELSE), expecting end of file. The code is probably terrible I have no clue what i am doing at all.</p>
<pre><code>I have tried altering the curly brackets but it still provides the same error
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO posts (userid, artist, link) VALUES ('2', '".$_POST["artist"]."', '".$_POST["link"]."')";
if (mysqli_query($conn, $sql)); {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
</code></pre>
| 0debug
|
static void test_qemu_strtosz_simple(void)
{
const char *str;
char *endptr = NULL;
int64_t res;
str = "0";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0);
g_assert(endptr == str + 1);
str = "12345";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 12345);
g_assert(endptr == str + 5);
res = qemu_strtosz(str, NULL);
g_assert_cmpint(res, ==, 12345);
str = "9007199254740991";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0x1fffffffffffff);
g_assert(endptr == str + 16);
str = "9007199254740992";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0x20000000000000);
g_assert(endptr == str + 16);
str = "9007199254740993";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0x20000000000000);
g_assert(endptr == str + 16);
str = "9223372036854774784";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0x7ffffffffffffc00);
g_assert(endptr == str + 19);
str = "9223372036854775295";
res = qemu_strtosz(str, &endptr);
g_assert_cmpint(res, ==, 0x7ffffffffffffc00);
g_assert(endptr == str + 19);
}
| 1threat
|
void av_blowfish_crypt(AVBlowfish *ctx, uint8_t *dst, const uint8_t *src,
int count, uint8_t *iv, int decrypt)
{
uint32_t v0, v1;
int i;
while (count > 0) {
if (decrypt) {
v0 = AV_RB32(src);
v1 = AV_RB32(src + 4);
av_blowfish_crypt_ecb(ctx, &v0, &v1, decrypt);
AV_WB32(dst, v0);
AV_WB32(dst + 4, v1);
if (iv) {
for (i = 0; i < 8; i++)
dst[i] = dst[i] ^ iv[i];
memcpy(iv, src, 8);
}
} else {
if (iv) {
for (i = 0; i < 8; i++)
dst[i] = src[i] ^ iv[i];
v0 = AV_RB32(dst);
v1 = AV_RB32(dst + 4);
} else {
v0 = AV_RB32(src);
v1 = AV_RB32(src + 4);
}
av_blowfish_crypt_ecb(ctx, &v0, &v1, decrypt);
AV_WB32(dst, v0);
AV_WB32(dst + 4, v1);
if (iv)
memcpy(iv, dst, 8);
}
src += 8;
dst += 8;
count -= 8;
}
}
| 1threat
|
static uint64_t lan9118_16bit_mode_read(void *opaque, target_phys_addr_t offset,
unsigned size)
{
switch (size) {
case 2:
return lan9118_readw(opaque, offset);
case 4:
return lan9118_readl(opaque, offset, size);
}
hw_error("lan9118_read: Bad size 0x%x\n", size);
return 0;
}
| 1threat
|
How can I Retrive the json Object Array Value using javascruipt : My Json Object Array is something like this:
country:[{ id: "1", name:"ajith", country:"india"},
{id: "2", name:"chandru", country:"india"},
{id:"3", name:"gane", country:"india"}]
how can i retrive these key and value, and how can i display in html table.
please anyone can please me. it's urgent.
| 0debug
|
static void gen_spr_970_lpar(CPUPPCState *env)
{
spr_register(env, SPR_970_HID4, "HID4",
SPR_NOACCESS, SPR_NOACCESS,
&spr_read_generic, &spr_write_generic,
0x00000000);
}
| 1threat
|
Using C# , I am trying to loop through a 2D array with a for loop using a string array with names . Info does not appear when I compile. : When I compile , the info from the array is not displayed. It will not show the name , phone number , or address. It will just come up blank. I followed many different examples using the for loop and I just can't get it to work , and there is no error message.
I appreciate anyone's input . Thank you.
string[,] customers = { { "Jay" , "123 Fake Street" , "212 111 1111"},
{" Pete" , "123 Fake Rd", "212 222 2222" },
{ "Will" , "112 Fake Av" , "212 333 3333"}, };
string cusName,
cusInfo;
bool phoneNumberFound = true;
Write("Enter your phone #:")
cusInfo = Convert.ToString(ReadLine());
for (int row = 0; row < customers.GetLength(0); ++row)
{
// Retreving the customers info from the array (second dimension of rows' width)
for (int col = 0; col < customers.GetLength(1); ++col)
{
if (phoneNumberFound)
{
cusInfo = customers[col, 0];
WriteLine();
WriteLine("Customer Name:\t", customers[row, col]);
WriteLine("Address:\t", customers[row, col]);
WriteLine("Phone Number:\t", customers[row, col]);
WriteLine();
//WriteLine("{0} , what size pizza do you want?:");
ReadLine();
}
else
{
WriteLine("Your phone number was not found , please enter your name:\t");
cusName = Convert.ToString(ReadLine());
}
}
}
}
}
}
}
| 0debug
|
Is it possiable to get Qlabel name from Qlabel text? : Our project, We have used Qlabels in different UI and different class.
like.
ui->label->setText(label_ABC);
we want to provide label name change access to the user.
default name already exists. if the user wants to change label name then first they change label_ABC to label_XYZ. this is saved in a database.
we want to replace lable_ABC to label_XYZ in all UI.
what is the best way to doing this?
| 0debug
|
i want last element of my arraylist and want to put it at 1st place : <p>I want my last element from my arraylist and i want to put it at 1st position of my arraylist and after that i want to remove my last element of an arraylist.</p>
<pre><code> public class Array {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] array = {13,25,35,74,5,16,73,8};
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter Value to Swipe:");
int position = sc.nextInt();
sc.nextLine();
List<Integer> NewArray = new ArrayList<Integer>();
if(position > array.length){
position = position % array.length;
}
for(int i = 0;i <= array.length-1;i++) {
NewArray.add(array[i]);
}
System.out.println(" "+NewArray);
for(int k = position;k <= position;k++) {
NewArray.add(0,NewArray.get(NewArray.size()));
System.out.println(" "+NewArray);
NewArray.remove(array.length);
}
System.out.println(" "+NewArray);
}
}
</code></pre>
| 0debug
|
How to send a message to a specific member? : <p>I'm making a bot with a function where I would like to send a message to a specific member.</p>
<p>How can I do to send a message to a specific member (with identification code such as "346176733549953029") rather than using message.author.send("the text I want to send") which send a message to the person who type the command?</p>
<p>I would need something like :</p>
<pre><code>message.user.get("346176733549953029").send("test I want to send");
</code></pre>
<p>The final should be for that member to receive a private message from the bot with the message inside...</p>
| 0debug
|
Convert simple program into lambda expression in python? : n=20
a=""
for i in range(1,n+1):
a+=str(i)+" "
print (a)
I don't know about `lambda` expression.Please Help me?
| 0debug
|
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->enc->codec_tag;
if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
(tag == MKTAG('d','v','c','p') ||
track->enc->codec_id == CODEC_ID_RAWVIDEO ||
track->enc->codec_id == CODEC_ID_H263 ||
av_get_bits_per_sample(track->enc->codec_id)))) {
if (track->enc->codec_id == CODEC_ID_DVVIDEO)
tag = mov_get_dv_codec_tag(s, track);
else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)
tag = mov_get_rawvideo_codec_tag(s, track);
else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {
tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
if (!tag) {
tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);
if (tag)
av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "
"the file may be unplayable!\n");
}
} else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {
tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
if (!tag) {
int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);
if (ms_tag) {
tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "
"the file may be unplayable!\n");
}
}
} else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)
tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);
}
return tag;
}
| 1threat
|
How is the git hash calculated? : <p>I'm trying to understand how git calculates the hash of refs. </p>
<pre><code>$ git ls-remote https://github.com/git/git
....
29932f3915935d773dc8d52c292cadd81c81071d refs/tags/v2.4.2
9eabf5b536662000f79978c4d1b6e4eff5c8d785 refs/tags/v2.4.2^{}
....
</code></pre>
<p>Clone the repo locally. Check the <code>refs/tags/v2.4.2^{}</code> ref by sha</p>
<pre><code>$ git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785
tree 655a20f99af32926cbf6d8fab092506ddd70e49c
parent df08eb357dd7f432c3dcbe0ef4b3212a38b4aeff
author Junio C Hamano <gitster@pobox.com> 1432673399 -0700
committer Junio C Hamano <gitster@pobox.com> 1432673399 -0700
Git 2.4.2
Signed-off-by: Junio C Hamano <gitster@pobox.com>
</code></pre>
<p>Copy the decompressed content so that we can hash it.(AFAIK git uses the uncompressed version when it's hashing)</p>
<pre><code>git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785 > fi
</code></pre>
<p>Let's SHA-1 the content using git's own hash command</p>
<pre><code>git hash-object fi
3cf741bbdbcdeed65e5371912742e854a035e665
</code></pre>
<p>Why the output is not <code>[9e]abf5b536662000f79978c4d1b6e4eff5c8d785</code>? I understand the first two characters (<code>9e</code>) is the length in hex. How should I hash the content of <code>fi</code> so that I can get the git ref <code>abf5b536662000f79978c4d1b6e4eff5c8d785</code> ?</p>
| 0debug
|
How to get input field value from Chrome Extension : <p>I am working to learn how to build a Google Chrome Extension. I have a contact form on a webpage that I'm using for testing. I'm trying to create an extension that will read the input field values from that form. At this time, I have:</p>
<p><strong>manifest.json</strong></p>
<pre><code>{
"manifest_version": 2,
"name": "Contact Form Friend",
"description": "This extension gets contact form info.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
}
</code></pre>
<p><strong>popup.html</strong></p>
<pre><code><!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style type="text/css">
body {
margin: 10px;
white-space: nowrap;
}
h1 {
font-size: 15px;
}
#container {
align-items: center;
display: flex;
justify-content: space-between;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<h1>Info</h1>
<div id="info">
</div>
</body>
</html>
</code></pre>
<p><strong>popup.js</strong></p>
<pre><code>function getHost() {
return document.documentElement;
}
document.addEventListener('DOMContentLoaded', () => {
const infoDisplay = document.getElementById('info');
const scriptToRun = `(${getHost})()`;
// Run the script in the context of the tab
chrome.tabs.executeScript({
code: scriptToRun
}, (result) => {
var values = [];
var inputFields = result.getElementsByTagName('input');
infoDisplay.innerHTML = 'inputs: ' + inputFields.length;
for (var i = 0; i < inputFields.length; i++) {
values.push(inputFields[i].value);
}
infoDisplay.innerHTML += '<br />fields: ' + values.length;
});
});
</code></pre>
<p>When I run this, it acts like it can't access the input fields from the web page the user is on (not the extension's web page). What am I doing wrong? Am I missing a permission? I don't believe so. However, it's not working and I'm not sure why.</p>
<p>Thank you for your help.</p>
| 0debug
|
static always_inline void gen_op_subfeo (void)
{
gen_op_move_T2_T0();
gen_op_subfe();
gen_op_check_subfo();
}
| 1threat
|
Wordpress: Default sorting by column of custom post type : <p>I have a custom post type called Contact, with custom fields like first name, surname, telephone number etc.</p>
<p>In the admin section they're sorted chronologically I think, but I need them to be sorted by surname by default.</p>
<p>I've read all the other solutions on here and none of them work, including:</p>
<pre><code>function set_post_order_in_admin( $wp_query ) {
global $pagenow;
if ( is_admin() && 'edit.php' == $pagenow && !isset($_GET['orderby'])) {
$wp_query->set( 'orderby', 'surname' );
$wp_query->set( 'order', 'ASC' );
}
}
add_filter('pre_get_posts', 'set_post_order_in_admin' );
</code></pre>
<p>But whatever field I try to sort by, nothing changes, except toggling ASC/DESC seems to change to reverse chronological ordering.</p>
<p>What am I doing wrong?</p>
| 0debug
|
I am trying to convert a pixel matrix into an image but its not working. Can anyone help me? Below is the code : public static Image getImageFromArray(int[] pixels, int width, int height) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0,0,width,height,pixels);
File output = new File("C:\\out.png");
ImageIO.write(image,"png",output);
System.out.print("written");
return image;
}
public static void main(String args[]) throws IOException{
int width, height;
BufferedImage source = ImageIO.read(new File(args[0]));
width=source.getWidth();
height=source.getHeight();
//Util obj = new Util();
Util.getImageFromArray(convertToPixels(source),width, height);
}
}
| 0debug
|
angular application not updating in realtime when article deleted or created : Angular application doesn't update in real time when I delete
deleteArticle(id){
this.articleService.deleteArticle(id).subscribe((article: Article)=>{
console.log("Article deleted, ", article);
});
}
The article gets deleted but I then need to refresh the browser to see the result?!
| 0debug
|
what is the command to get the starting character of file in unix : Below is the filename
-rwxrwxrwx 1 user1 users 268 Sep 16 18:06 script
what should be the command to grep the first character here
based on that i want to conclude it as file or directory or a softlink.
can we use the wildcard "^" to get this info please?
| 0debug
|
static void test_qemu_strtoull_decimal(void)
{
const char *str = "0123";
char f = 'X';
const char *endptr = &f;
uint64_t res = 999;
int err;
err = qemu_strtoull(str, &endptr, 10, &res);
g_assert_cmpint(err, ==, 0);
g_assert_cmpint(res, ==, 123);
g_assert(endptr == str + strlen(str));
str = "123";
endptr = &f;
res = 999;
err = qemu_strtoull(str, &endptr, 0, &res);
g_assert_cmpint(err, ==, 0);
g_assert_cmpint(res, ==, 123);
g_assert(endptr == str + strlen(str));
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.