problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
Want to make a multi page navigation menu "HTML, JS, jQuery, Bootstrap" : <p>Hello i have been looking for a answer with no luck.</p>
<p>Im looking for a way to clean up my code by having a navigation bar that i can add to other pages with ease. </p>
<p>I have been trying hard to get this right but whitout luck. Hope i can get an answer here.</p>
<p>Im using the Bootstrap library and would be wonderful if someone out there would help me out.</p>
<p>HTML code you will find below.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<title>Bootstrap 4 Layout</title>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:400,800">
<link rel='stylesheet' href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<!--Main Menu-->
<div class="container">
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="#">CompanyName</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" data-toggle="dropdown">
Products
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Product 1</a>
<a class="dropdown-item" href="#">Product 2</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Another Product</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
<!--Futured posts-->
<div class="jumbotron">
<h1 class="display-4">Simple. Elegant. Awesome.</h1>
<p class="lead">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
<p class="lead">
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</p>
</div>
<!--Roster Cards-->
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="card mb-4">
<div class="card-body text-center">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title</p>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="card mb-4">
<div class="card-body text-center">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title</p>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="card mb-4">
<div class="card-body text-center">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title</p>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
</div>
<div class="row mt-sm-4 mt-md-0">
<div class="col-sm-12 col-md-8 text-sm-center text-md-left">
<h3>An important heading</h3>
<p class="lead">A sort of important subheading can go here, which is larger and gray.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
<div class="col-sm-12 col-md-4">
<h3 class="mb-4">Secondary Menu</h3>
<ul class="nav flex-column nav-pills">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</div>
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| 0debug
|
Javascript: Array doesn't work : <p>I need some help from you guys!</p>
<p>This is my JS code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray[2] = "Hi";</code></pre>
</div>
</div>
</p>
<p>It says: "SyntaxError: missing ; before statement".</p>
<p>I dont't see where the hell I forgot an ";" in the easiest code ever.</p>
| 0debug
|
how to change the column format "yyyy-mm-dd" to "yyyy-mm-dd in mysql : i want to change the format of column ENROLLED_ON "yyyy-mm-dd" to "mmm-yy". please help.
ENROLLED_ON | ENROLLED_ON
------------| ------
yyyy-mm-dd | mmm-yy
| 0debug
|
Java or python which is better to do Automation using Selenium : <p>Java or python which is better to do Automation using Selenium. since I don't have an idea about python, so please suggest me if python is better than Java for automation.</p>
| 0debug
|
swift 3 delegate not work : I' ve this swift code where I've create a delegate but this not work correctly. I not understand where I wrong
protocol MenuDelegate {
func upateUserProfileImage()
}
// Userprofile view
class UserProfileViewController: UIViewController {
var delegate : MenuDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate?.upateUserProfileImage()
}
}
class MenuViewController: UIViewController, MenuDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func upateUserProfileImage() {
print("Work!")
}
}
Thanks for help!!
| 0debug
|
static int compensate_volume(AVFilterContext *ctx)
{
struct SOFAlizerContext *s = ctx->priv;
float compensate;
float energy = 0;
float *ir;
int m;
if (s->sofa.ncid) {
struct NCSofa *sofa = &s->sofa;
m = find_m(s, 0, 0, 1);
ir = sofa->data_ir + 2 * m * sofa->n_samples;
if (sofa->n_samples & 31) {
energy = avpriv_scalarproduct_float_c(ir, ir, sofa->n_samples);
} else {
energy = s->fdsp->scalarproduct_float(ir, ir, sofa->n_samples);
}
compensate = 256 / (sofa->n_samples * sqrt(energy));
av_log(ctx, AV_LOG_DEBUG, "Compensate-factor: %f\n", compensate);
ir = sofa->data_ir;
s->fdsp->vector_fmul_scalar(ir, ir, compensate, sofa->n_samples * sofa->m_dim * 2);
emms_c();
}
return 0;
}
| 1threat
|
void migration_set_outgoing_channel(MigrationState *s,
QIOChannel *ioc)
{
QEMUFile *f = qemu_fopen_channel_output(ioc);
s->to_dst_file = f;
migrate_fd_connect(s);
}
| 1threat
|
Split the sub String from a String Starting with "http" and ending with ".JPG" in Excel : For Example Here is the String in Cell A1:
Product Image File: 2eeb_1_edse.JPG Product Image URL: http://www.example.com/product_images/p/759/2eeb_1_edse.JPG|Product Image File: r__006677.jpg, Product Image URL: http://www.example.com/product_images/e/130/r__006677.jpg
It Contains two Image URLs I want to Populate These two URLs in Cell B1 and C1.
Please Any Body Can Help ?
| 0debug
|
Converting String to Integer. Why this error? I want to change the ID (string) to IC (integer). Both are arrays. I'm still a beginner by the way. : #include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
int main(){
string ID[]={"620301025123"}; //ID array
long long int IC[10]={0}; //IC array
// loop to change the ID string to Array IC. I will want to increase the size of ID array, later on, to put in new data but for now, I'm just using one data which is "620301025123" first. */
for(int i = 0; i < 10; ++i){
IC[i]= {atoll(ID[i].c_str())};
}
}
/*The error I got is :
14 29 C:\Users\ASUS\Desktop\Assign1\Untitled3.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11*/
//[1]: https://i.stack.imgur.com/qTGQ3.jpg
| 0debug
|
'str' does not support the buffer interface : I want to select those sentences which contains some conjunctions mentioned.But I am getting an error as:Traceback (most recent call last): File "positive_process3.py", line 14, in <module> if word in text: TypeError: 'str' does not support the buffer interface.
My code is:
import xlrd
from xlrd import open_workbook
import xlwt
wb = open_workbook("C:/Users/SA769740/Desktop/result2/pos.xlsx")
book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("Sheet 1")
wordSet = [' for ', ' so ',' since ', ' Since ', ' because ', ' as ', ' As ', ' due to ', ' Due to ']
count=1
for sheet in wb.sheets():
for row in range(sheet.nrows):
text = ((sheet.cell(row,2).value).encode("utf-8"))
l = ""
for word in wordSet:
if word in text:
l += (word+" ")
sheet1.write(row,0,sheet.cell(row, 0).value)
sheet1.write(row,3, l)
sheet1.write(row,4,count)
sheet1.write(row,5,value)
count += 1
book.save('C:/Users/SA769740/Desktop/result2/pos_reviews_process3.xls')
I am using python 2.7.Error:line 14, in <module> **if word in text**: TypeError: 'str' does not support the buffer interface
| 0debug
|
cpu_x86_dump_seg_cache(CPUX86State *env, FILE *f, fprintf_function cpu_fprintf,
const char *name, struct SegmentCache *sc)
{
#ifdef TARGET_X86_64
if (env->hflags & HF_CS64_MASK) {
cpu_fprintf(f, "%-3s=%04x %016" PRIx64 " %08x %08x", name,
sc->selector, sc->base, sc->limit, sc->flags & 0x00ffff00);
} else
#endif
{
cpu_fprintf(f, "%-3s=%04x %08x %08x %08x", name, sc->selector,
(uint32_t)sc->base, sc->limit, sc->flags & 0x00ffff00);
}
if (!(env->hflags & HF_PE_MASK) || !(sc->flags & DESC_P_MASK))
goto done;
cpu_fprintf(f, " DPL=%d ", (sc->flags & DESC_DPL_MASK) >> DESC_DPL_SHIFT);
if (sc->flags & DESC_S_MASK) {
if (sc->flags & DESC_CS_MASK) {
cpu_fprintf(f, (sc->flags & DESC_L_MASK) ? "CS64" :
((sc->flags & DESC_B_MASK) ? "CS32" : "CS16"));
cpu_fprintf(f, " [%c%c", (sc->flags & DESC_C_MASK) ? 'C' : '-',
(sc->flags & DESC_R_MASK) ? 'R' : '-');
} else {
cpu_fprintf(f, (sc->flags & DESC_B_MASK) ? "DS " : "DS16");
cpu_fprintf(f, " [%c%c", (sc->flags & DESC_E_MASK) ? 'E' : '-',
(sc->flags & DESC_W_MASK) ? 'W' : '-');
}
cpu_fprintf(f, "%c]", (sc->flags & DESC_A_MASK) ? 'A' : '-');
} else {
static const char *sys_type_name[2][16] = {
{
"Reserved", "TSS16-avl", "LDT", "TSS16-busy",
"CallGate16", "TaskGate", "IntGate16", "TrapGate16",
"Reserved", "TSS32-avl", "Reserved", "TSS32-busy",
"CallGate32", "Reserved", "IntGate32", "TrapGate32"
},
{
"<hiword>", "Reserved", "LDT", "Reserved", "Reserved",
"Reserved", "Reserved", "Reserved", "Reserved",
"TSS64-avl", "Reserved", "TSS64-busy", "CallGate64",
"Reserved", "IntGate64", "TrapGate64"
}
};
cpu_fprintf(f, "%s",
sys_type_name[(env->hflags & HF_LMA_MASK) ? 1 : 0]
[(sc->flags & DESC_TYPE_MASK)
>> DESC_TYPE_SHIFT]);
}
done:
cpu_fprintf(f, "\n");
}
| 1threat
|
static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
{
PerThreadContext *p = avctx->internal->thread_ctx;
int err;
f->owner = avctx;
ff_init_buffer_info(avctx, f->f);
if (!(avctx->active_thread_type & FF_THREAD_FRAME))
return ff_get_buffer(avctx, f->f, flags);
if (atomic_load(&p->state) != STATE_SETTING_UP &&
(avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
return -1;
}
if (avctx->internal->allocate_progress) {
atomic_int *progress;
f->progress = av_buffer_alloc(2 * sizeof(*progress));
if (!f->progress) {
return AVERROR(ENOMEM);
}
progress = (atomic_int*)f->progress->data;
atomic_init(&progress[0], -1);
atomic_init(&progress[1], -1);
}
pthread_mutex_lock(&p->parent->buffer_mutex);
if (avctx->thread_safe_callbacks ||
avctx->get_buffer2 == avcodec_default_get_buffer2) {
err = ff_get_buffer(avctx, f->f, flags);
} else {
pthread_mutex_lock(&p->progress_mutex);
p->requested_frame = f->f;
p->requested_flags = flags;
atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
pthread_cond_broadcast(&p->progress_cond);
while (atomic_load(&p->state) != STATE_SETTING_UP)
pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
err = p->result;
pthread_mutex_unlock(&p->progress_mutex);
}
if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
ff_thread_finish_setup(avctx);
if (err)
av_buffer_unref(&f->progress);
pthread_mutex_unlock(&p->parent->buffer_mutex);
return err;
}
| 1threat
|
Firestore - Delete a field inside an object : <p>I'm using Firestore and I would like to delete a field that is in a specific object.
I can delete a field in a document thanks to : </p>
<pre><code>fieldName: firebase.firestore.FieldValue.delete()
</code></pre>
<p>But if I have an object like : </p>
<pre><code>songList {
songName1: "HelloWorld",
songName2: "AnotherSong",
songName3: "andTheLastOne"
}
</code></pre>
<p>In order to delete the field songName3, I won't be able to do something like : </p>
<pre><code>songList.songName3: firebase.firestore.FieldValue.delete()
</code></pre>
<p>Is there a way to delete a field inside an object ? Or should I delete the whole object, rebuild it without the 3rd field and save it ?</p>
<p>Thanks in advance,</p>
| 0debug
|
How to set up Travis CI and postgresql using custom db credentials? : <p>I'm trying to set up custom Postgres credentials with Travis CI as I'd like to avoid the existing credentials definition in the code to be tested.</p>
<p>The testing code defines that the database should be accessed on: </p>
<pre><code>'sqlalchemy.url': 'postgresql://foo:bar@localhost/testing_db'
</code></pre>
<p>I've therefore created a <code>database.travis.yml</code> file:</p>
<pre><code>postgresql: &postgresql
adapter: postgresql
username: foo
password: bar
database: testing_db
</code></pre>
<p>...and added the following to my <code>.travis.yml</code>:</p>
<pre><code>services:
- postgresql
before_script:
- psql -c 'create database stalker_test;' -U postgres
- mkdir config && cp database.travis.yml config/database.yml
</code></pre>
<p>However, I am still getting this during testing:</p>
<pre><code>OperationalError: (psycopg2.OperationalError) FATAL: role "foo" does not exist
</code></pre>
<p>What am I doing wrong?</p>
| 0debug
|
Scikit-learn, get accuracy scores for each class : <p>Is there a built-in way for getting accuracy scores for each class separatetly? I know in sklearn we can get overall accuracy by using <code>metric.accuracy_score</code>. Is there a way to get the breakdown of accuracy scores for individual classes? Something similar to <code>metrics.classification_report</code>.</p>
<pre><code>from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']
</code></pre>
<p><code>classification_report</code> does not give accuracy scores:</p>
<pre><code>print(classification_report(y_true, y_pred, target_names=target_names, digits=4))
Out[9]: precision recall f1-score support
class 0 0.5000 1.0000 0.6667 1
class 1 0.0000 0.0000 0.0000 1
class 2 1.0000 0.6667 0.8000 3
avg / total 0.7000 0.6000 0.6133 5
</code></pre>
<p>Accuracy score gives only the overall accuracy:</p>
<pre><code>accuracy_score(y_true, y_pred)
Out[10]: 0.59999999999999998
</code></pre>
| 0debug
|
How to get dinamic path in java : String s = "cmd /c " + GeneralMethods.getFilesPath()
+ "mysql-5.6.26-winx64/bin/mysqldump -u root -password database_name>" + GeneralMethods.getFilesPath()
+ "backup/backup.sql";
I dont want to static code
I want to chose dinamic path on java
can someone help me?
| 0debug
|
Nested arrays - how to add a row of elements to nested JavaScript array : <p>I want to add the row</p>
<pre><code> ['2008',777,333]
</code></pre>
<p>to var fun and maintain the structure:</p>
<pre><code>var fun = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
];
</code></pre>
<p>Using push or concat seems to destroy the structure. Can this be done?</p>
| 0debug
|
static BlockDriverAIOCB *dma_bdrv_io(
BlockDriverState *bs, QEMUSGList *sg, uint64_t sector_num,
BlockDriverCompletionFunc *cb, void *opaque,
int is_write)
{
DMABlockState *dbs = qemu_malloc(sizeof(*dbs));
dbs->bs = bs;
dbs->acb = qemu_aio_get(bs, cb, opaque);
dbs->sg = sg;
dbs->sector_num = sector_num;
dbs->sg_cur_index = 0;
dbs->sg_cur_byte = 0;
dbs->is_write = is_write;
dbs->bh = NULL;
qemu_iovec_init(&dbs->iov, sg->nsg);
dma_bdrv_cb(dbs, 0);
return dbs->acb;
}
| 1threat
|
static void pci_bridge_write_config(PCIDevice *d,
uint32_t address, uint32_t val, int len)
{
PCIBridge *s = (PCIBridge *)d;
if (address == 0x19 || (address == 0x18 && len > 1)) {
if (address == 0x19)
s->bus->bus_num = val & 0xff;
else
s->bus->bus_num = (val >> 8) & 0xff;
#if defined(DEBUG_PCI)
printf ("pci-bridge: %s: Assigned bus %d\n", d->name, s->bus->bus_num);
#endif
}
pci_default_write_config(d, address, val, len);
}
| 1threat
|
int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
int *got_picture_ptr,
const AVPacket *avpkt)
{
int ret;
AVPacket tmp = *avpkt;
if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
return AVERROR(EINVAL);
}
*got_picture_ptr= 0;
if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
return -1;
if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
int did_split = av_packet_split_side_data(&tmp);
apply_param_change(avctx, &tmp);
avctx->pkt = &tmp;
if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
&tmp);
else {
ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
&tmp);
picture->pkt_dts= avpkt->dts;
if(!avctx->has_b_frames){
picture->pkt_pos= avpkt->pos;
}
if (!picture->sample_aspect_ratio.num)
picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
if (!picture->width)
picture->width = avctx->width;
if (!picture->height)
picture->height = avctx->height;
if (picture->format == PIX_FMT_NONE)
picture->format = avctx->pix_fmt;
}
emms_c();
avctx->pkt = NULL;
if (did_split) {
ff_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (*got_picture_ptr){
avctx->frame_number++;
picture->best_effort_timestamp = guess_correct_pts(avctx,
picture->pkt_pts,
picture->pkt_dts);
}
}else
ret= 0;
return ret;
}
| 1threat
|
Could not install package '--'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5' : <p>I created this package, I need it in a project but couldn't install it, this error appears:</p>
<blockquote>
<p>Could not install package 'Mshwf.NiceLinq 1.0.9'. You are trying to
install this package into a project that targets
'.NETFramework,Version=v4.5', but the package does not contain any
assembly references or content files that are compatible with that
framework. For more information, contact the package author</p>
</blockquote>
<p>I don't know why this happen, in another project (Console) I changed the framework to 4.6 and other versions and it wasn't a problem, but this only happen in this project (MVC and Web API):</p>
<p>this is the nuspec file:</p>
<pre><code><?xml version="1.0"?>
<package >
<metadata>
<id>Mshwf.NiceLinq</id>
<version>1.0.9</version>
<title>Nice LINQ</title>
<authors>MShawaf</authors>
<owners>Mshawaf</owners>
<projectUrl>https://github.com/mshwf/NiceLinq</projectUrl>
<iconUrl>https://raw.githubusercontent.com/mshwf/NiceLinq/master/logo.png</iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>See it as: WHERE ID IN (1, 2, 3, 7, 9, 22, 30, 101)</description>
<releaseNotes>Minor changes.</releaseNotes>
<copyright>Copyright 2016</copyright>
<tags>LINQ IEnumerable Where Contains Search Filter</tags>
</metadata>
</package>
</code></pre>
| 0debug
|
static inline int find_pte (CPUState *env, mmu_ctx_t *ctx, int h, int rw)
{
#if defined(TARGET_PPC64)
if (env->mmu_model == POWERPC_MMU_64B ||
env->mmu_model == POWERPC_MMU_64BRIDGE)
return find_pte64(ctx, h, rw);
#endif
return find_pte32(ctx, h, rw);
}
| 1threat
|
Trouble retriving Value from dictionary C# : I've seen a few similar questions but I've been unable to find a suitable answer so far. I'm coding a client and a server for a project, where the client will submit a user and their location to the server. The server will then store this information in a dictionary.
Here is the client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class Whois
{
static void Main(string[] args)
{
TcpClient client = new TcpClient();
try
{
client.Connect("localhost", 43);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
if (args.Length == 2)
{
sw.WriteLine(args[0] + " " + args[1]);
sw.Flush();
sw.Close();
sr.Close();
Console.Read();
}
else
{
sw.WriteLine(args[0]);
sw.Flush();
sw.Close();
sr.Close();
//Console.WriteLine(args[0] + " is " + sr.ReadToEnd());
Console.Read();
}
}
catch
{
Console.WriteLine("Something went wrong there, surprisingly.");
}
}
}
And here is the server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace locationserver
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
RunServer(dictionary);
}
static void RunServer(Dictionary<string, string> dictionary)
{
Console.Clear();
TcpListener listener;
Socket connection;
NetworkStream socketStream;
Console.WriteLine("Dictionary list -----------------");
List<string> list = new List<string>(dictionary.Keys);
foreach (string k in list)
{
Console.WriteLine("{0}, {1}", k, dictionary[k]);
}
Console.WriteLine("---------------------------------");
try
{
listener = new TcpListener(IPAddress.Any, 43);
listener.Start();
Console.WriteLine("Server started listening...");
while (true)
{
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
DoRequest(socketStream, dictionary, listener);
//socketStream.Close();
//connection.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
RunServer(dictionary);
}
}
static void DoRequest(NetworkStream inputStream, Dictionary<string, string> dictionary, TcpListener listener)
{
string[] temp;
string streamInput;
StreamWriter sw = new StreamWriter(inputStream);
StreamReader sr = new StreamReader(inputStream);
streamInput = sr.ReadToEnd();
if (streamInput.Contains(" "))
{
temp = streamInput.Split(' ');
dictionary.Add(temp[0], temp[1]);
listener.Stop();
RunServer(dictionary);
}
else
{
try
{
Console.WriteLine(streamInput);
Console.WriteLine(dictionary[streamInput]);
Console.ReadLine();
listener.Stop();
RunServer(dictionary);
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
listener.Stop();
RunServer(dictionary);
}
}
}
}
}
The client is succesfully transmitting the data to the server, and the server prints out the dictionary at once the data has been recieved for the purpose of error checking, yet when I try to access the key's corresponding value in the dictionary, it isn't there. Any help would be great.
| 0debug
|
void OPPROTO op_srli_T1 (void)
{
T1 = T1 >> PARAM1;
RETURN();
}
| 1threat
|
automatically convert string to appropriate type : <p>I am trying to find a function to have python automatically convert a string to the "simplest" type. Some examples:</p>
<pre><code>conversion_function("54") -> returns an int 54
conversion_function("6.34") -> returns a float 6.34
conversion_function("False") -> returns a boolean False
conversion_function("text") -> returns a str "text"
</code></pre>
<p>R has a function called <a href="https://stat.ethz.ch/R-manual/R-devel/library/utils/html/type.convert.html" rel="nofollow noreferrer">type.convert</a> that does this. What is the way to do this in python? Is there an existing function or does one need to create a custom one?</p>
| 0debug
|
Create new column based on partial string matching of other column (several patterns) R : In the post http://stackoverflow.com/questions/19747384/how-to-create-new-column-in-dataframe-based-on-partial-string-matching-other-col there is the answer to this question, but I am not able to apply it to my data.
The problem is that in the column "Fertiliser" (strings) the amount of different types of fertiliser. The third number refers to manure. I want to create a new column which only the amount of manure (so then I can do regression analysis against yield).
`Fertiliser millet_biomass millet_yield
1: 0-0-0 2659.608 710.6942
2: 0-0-100 2701.044 718.1154
3: 0-0-2700 3415.879 804.0360
4: 0-0-300 2781.639 730.5943
5: 0-0-900 2997.173 760.0136
6: 12-4-0 3703.255 772.1719
7: 12-4-100 3720.247 773.1759
8: 12-4-2700 3950.189 788.6133
9: 12-4-300 3751.400 775.1368
10: 12-4-900 3826.693 780.2623
11: 30-10-0 4180.323 798.2134
12: 30-10-100 4184.229 798.4918
13: 30-10-2700 4217.044 800.9312
14: 30-10-300 4187.014 798.6570
15: 30-10-900 4194.873 799.2085
16: 6-2-0 3296.274 765.8496
17: 6-2-100 3326.844 767.6693
18: 6-2-2700 3772.058 785.4535
19: 6-2-300 3381.152 760.7330
20: 6-2-900 3517.515 768.3018
21: 90-30-0 4542.924 831.2832
22: 90-30-100 4543.036 831.3983
23: 90-30-2700 4545.037 831.3227
24: 90-30-300 4543.240 831.3921
25: 90-30-900 4543.733 831.3727`
Thus, there are five patterns patterns "-0$","-100$","-300$","-900$","270$",
which need to be replaced by "0", "100","300","900","2700"
I appreciate any help.
| 0debug
|
Push files to gitlab-ci via CI runner : <p>I am using gitlab CI runner to test my code and generating some files. I just want to push the generated files to gitlab repository via CI runner. Is there any way to do that ?</p>
| 0debug
|
static int img_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
{
VideoData *img = s->priv_data;
AVStream *st;
AVImageFormat *img_fmt;
int i;
if (ap && ap->image_format) {
img_fmt = ap->image_format;
} else {
img_fmt = guess_image_format(s->filename);
}
if (!img_fmt)
return -1;
if (s->nb_streams != 1)
return -1;
st = s->streams[0];
for(i=0;i<PIX_FMT_NB;i++) {
if (img_fmt->supported_pixel_formats & (1 << i))
break;
}
if (i >= PIX_FMT_NB)
return -1;
img->img_fmt = img_fmt;
img->pix_fmt = i;
st->codec->pix_fmt = img->pix_fmt;
return 0;
}
| 1threat
|
import re
def capital_words_spaces(str1):
return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)
| 0debug
|
How to convert an integer to byte literal in Rust? : <p>I am trying to convert an integer to byte literal in Rust:</p>
<pre><code>for x in 0..10000 {
let key = x.to_???;
other_function(key);
}
</code></pre>
<p>Could not find it in the docs.</p>
| 0debug
|
Multiple aiohttp Application()'s running in the same process? : <p>Can two <code>aiohttp.web.Application()</code> objects be running in the same process, e.g. on different ports?</p>
<p>I see a bunch of examples of aiohttp code like:</p>
<pre><code>from aiohttp import web
app = web.Application()
app.router.add_get('/foo', foo_view, name='foo')
web.run_app(app, host='0.0.0.0', port=10000)
</code></pre>
<p>I'm wondering if there's some equivalent where multiple <code>web.Applications()</code> can be configured to run at the same time. Something like:</p>
<pre><code>from aiohttp import web
app1 = web.Application()
app1.router.add_get('/foo', foo_view, name='foo')
app2 = web.Application()
app2.router.add_get('/bar', bar_view, name='bar')
# This is the wishful thinking code:
web.configure_app(app1, host='0.0.0.0', port=10000)
web.configure_app(app2, host='0.0.0.0', port=10001)
web.run_apps()
</code></pre>
<p>My use case is that I have an existing python web framework that does this kind of thing, and I'm building a prototype that's analogous in python 3.6 with aiohttp.</p>
<p>I understand that multiple python servers can run behind e.g. nginx (see also <a href="http://aiohttp.readthedocs.io/en/stable/deployment.html" rel="noreferrer">http://aiohttp.readthedocs.io/en/stable/deployment.html</a>); that's not what I'm after. I want to explore the possibility of two aiohttp web servers with the same asyncio event loop, running in the same python process, serving on two different ports.</p>
| 0debug
|
How to access array within PHP object : <p>I know this question is a little n00b but I am struggling to work out to how to access the array 'ta[]' within the PHP object below. Usually I would have no problem but because my key contains the brackets i.e. 'ta[]' I can't wrap my head around how to access it, I guess I somehow need to escape it..?</p>
<p>I have tried most combinations such as..</p>
<pre><code>object->ta[]
object["ta[0]"]
object["ta[]"]
object->ta[0]
</code></pre>
<p>Any help welcome!</p>
<pre><code>object(stdClass)#6 (11) {
["tc"]=> string(4) "4500"
["tct"]=> string(1) "1"
["pd"]=> string(2) "AT"
["df"]=> string(10) "08/04/2016"
["dt"]=> string(10) "08/08/2016"
["nt"]=> string(1) "2"
["ta[]"]=> array(2)
{
[0]=> string(2) "40"
[1]=> string(2) "35"
}
["rc"]=> string(2) "US"
["rs"]=> string(2) "AR"
["cc"]=> string(2) "US"
["dfp"]=> string(10) "07/30/2016"
}
</code></pre>
| 0debug
|
Table: Fixed thead durgin scroll with JS : I am trying to **fix** the **thead** on this [table][1] when you scroll the table, but without any results.
This is the JS i tried:
<script>
document.getElementById("tablepress-10").addEventListener("scroll", function() {
var translate = "translate(0," + this.scrollTop + "px)";
this.querySelector("thead").style.transform = translate;
});
</script>
Any tips?
Thanks in advice.
**PS: I am using Wordpress**
[1]: http://ap.nowcommu.myhostpoint.ch/434-2/
| 0debug
|
Transitioning from sqlalchemy to postgres database : I've been using Flask with sqlalchemy but I've transitioned to setting up my own postgres databases and using psycopg2 to insert and return values from my databases. I was wondering how the classes in my Model.py should change now that I'm no longer using the databases set up by sqlalchemy and whether I need to set up a db object at all anymore.
Setting up a db object:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db.SQLALCHEMY(app)
A sample of a class in my Model file:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
zipAddress = db.Column(db.String(64))
| 0debug
|
Tensorflow: Multiple loss functions vs Multiple training ops : <p>I am creating a Tensorflow model which predicts multiple outputs (with different activations). I think there are two ways to do this:</p>
<p><strong>Method 1:</strong> Create multiple loss functions (one for each output), merge them (using <code>tf.reduce_mean</code> or <code>tf.reduce_sum</code>) and pass it to the training op like so:</p>
<pre><code>final_loss = tf.reduce_mean(loss1 + loss2)
train_op = tf.train.AdamOptimizer().minimize(final_loss)
</code></pre>
<p><strong>Method 2:</strong> Create multiple training operations and then group them like so:</p>
<pre><code>train_op1 = tf.train.AdamOptimizer().minimize(loss1)
train_op2 = tf.train.AdamOptimizer().minimize(loss2)
final_train_op = tf.group(train_op1 train_op2)
</code></pre>
<p>My question is whether one method is advantageous over the other? Is there a third method I don't know?</p>
<p>Thanks</p>
| 0debug
|
php header works fine with local host but does not work with real server : I am trying to header my page in real server but it does not work, I try it in xamp localhost it work fine :|?
if(empty($_POST)===false){
include_once("db.php");
$username = $_POST['user'];
$pwd = $_POST['pwd'];
$rs = mysqli_query($con,"select *from admin_acc where username = '".$username."'");
$num_rows = mysqli_num_rows($rs);
if($num_rows > 0){
while($rows = mysqli_fetch_assoc($rs))
{
$db_username = $rows['username'];
}
if($username == $db_username && md5($pwd) == $db_password){
$_SESSION['username'] = $db_username;
//Header to Home Page
header('Location: customers.php');
}else{
$wrng_pwd = "Wrong Password!";
$msg_type = 1;
}
}else{
$user_nt = "User name not exsit!!";
$msg_type = 2;
}
}
So can you please help me guys? because I was looking for the answer throw the internet but I have not find a good answer
| 0debug
|
void monitor_init(CharDriverState *hd, int show_banner)
{
int i;
if (is_first_init) {
key_timer = qemu_new_timer(vm_clock, release_keys, NULL);
if (!key_timer)
return;
for (i = 0; i < MAX_MON; i++) {
monitor_hd[i] = NULL;
}
is_first_init = 0;
}
for (i = 0; i < MAX_MON; i++) {
if (monitor_hd[i] == NULL) {
monitor_hd[i] = hd;
break;
}
}
hide_banner = !show_banner;
qemu_chr_add_handlers(hd, term_can_read, term_read, term_event, NULL);
readline_start("", 0, monitor_handle_command1, NULL);
}
| 1threat
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
Can't find the offical documentation for the next() method :
I see it is used in various ways: next(), next('route'), next(error)...
Where can I find the official documentation for the `next()` method ?
I don't find any documentation summing up it's use cases on the [express api docs][1]...
[1]: http://expressjs.com/en/4x/api.html
| 0debug
|
I am using Python 3 and want to turn something into a while loop : I am using Python 3 and want to turn something into a while loop but I am new so I am having some trouble with this.
PS - sorry if the code below has wrong indentations, as I am still getting used to stack overflow, they are correct in my program
username_chosen = input("Enter the username of the user for their details :")
with open("data.txt") as f:
for line in f:
if username_chosen in line:
print(line)
The loop I want is where the program keeps checking if there is a username as the one entered by the user and if there is not then it tells them error and prompts them to input again until the program can find the username.
| 0debug
|
waht is the meaning of <> " angular bracket" in javascript : I using vscode for javascript. for example when i writing a filter on an array vscode shows me this documentation for callback function:
>"< S extends T >(callbackfn: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[]
"
i see <> in typescript code but can't understand concept of it.
what does that angular brackets means?
| 0debug
|
Is crashing the program when go into line "private TextView name = new TextView(this);" : Help, guys!I am creating the simple phone book I don`t know what is the trouble, i have two classes: MainActivity and Abonent, so abonent gives all necessary info to class MainActivity then this info should be outputted on the screen, but when it goes into the class Abonent and then to link "private TextView name = new TextView(this);", the program is crushing.
Here is a code:
public class MainActivity extends AppCompatActivity {
LinearLayout main, submain;
LinearLayout.LayoutParams main_param, submain_param;
protected void onCreate(Bundle savedInstanceState) {
//Initializing
main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
main.setBackgroundColor(getColor(R.color.myblue));
main_param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
super.onCreate(savedInstanceState);
setContentView(main, main_param);
for(int i = 0; i < 4; i++) {
Abonent abn = new Abonent("Kathrine", 0x7f020054 + i , "+38096" + i);
submain= new LinearLayout(this);
submain.setOrientation(LinearLayout.HORIZONTAL);
submain_param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
submain_param.bottomMargin = 40;
main.addView(abn.getName(), abn.name_param);
submain.addView(abn.getIcon(), abn.icon_param);
submain.addView(abn.getNumber(), abn.number_param);
main.addView(submain, submain_param);
}
}
}
public class Abonent extends MainActivity{
public Abonent(String name, int iconId, String number){
setName(name);
setNumber(number);
setIcon(iconId);
}
final LinearLayout.LayoutParams name_param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final LinearLayout.LayoutParams icon_param = new LinearLayout.LayoutParams(250, 250);
final LinearLayout.LayoutParams number_param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
private TextView name = new TextView(this);
private ImageView icon = new ImageView(this);
private TextView number = new TextView(this);
//private Button call = new Button(this);
private SpannableString content;
private void setName(String name){
content = new SpannableString(name);
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
this.name.setText(content);
this.name.setTextColor(getResources().getColor(R.color.myblack));
this.name.setTextSize(30);
this.name_param.leftMargin = 40;
}
private void setNumber(String number){
content = new SpannableString(number);
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
this.number.setText(content);
this.number.setTextColor(getResources().getColor(R.color.myblack));
this.number.setBackgroundColor(getResources().getColor(R.color.myblue));
this.number.setTextSize(30);
this.number_param.leftMargin = 40;
}
private void setIcon(int iconId){
this.icon.setImageResource(iconId);
}
public TextView getName(){
return this.name;
}
public TextView getNumber(){
return this.name;
}
public ImageView getIcon(){
return this.icon;
}
}
| 0debug
|
Adventages to using foreach in relation to for : Hi in first i'm sorry for my bad English level, i work it :P
I have a question, what is the avantages to use a **forEach** loop in relation to a **for** boucle ?
Tkanks for your answers :P
| 0debug
|
void hmp_info_tlb(Monitor *mon, const QDict *qdict)
{
CPUArchState *env1 = mon_get_cpu_env();
dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);
| 1threat
|
int pci_vga_init(PCIBus *bus,
unsigned long vga_bios_offset, int vga_bios_size)
{
PCIDevice *dev;
dev = pci_create(bus, -1, "VGA");
qdev_prop_set_uint32(&dev->qdev, "bios-offset", vga_bios_offset);
qdev_prop_set_uint32(&dev->qdev, "bios-size", vga_bios_offset);
qdev_init(&dev->qdev);
return 0;
}
| 1threat
|
How to padding for macOS google chrome? : <p>i would like to apply some padding in css for only Chrome on Mac, i've looked around but not found a solution.</p>
<p>I have tried webkits but dont seem to solve the issue.</p>
| 0debug
|
Assigning a1<-1, a2<-2, a3<- using for loop in r : <p>I want to make</p>
<pre><code>a1 <- 1
a2 <- 2
a3 <- 3
</code></pre>
<p>I want to use</p>
<pre><code>for (i in 1:3) {
paste("a",i) <- i
}
</code></pre>
<p>but this clearly doesn't work.
Is there any way to this kind of stuff easily?</p>
| 0debug
|
void xen_map_cache_init(void)
{
unsigned long size;
struct rlimit rlimit_as;
mapcache = g_malloc0(sizeof (MapCache));
QTAILQ_INIT(&mapcache->locked_entries);
mapcache->last_address_index = -1;
if (geteuid() == 0) {
rlimit_as.rlim_cur = RLIM_INFINITY;
rlimit_as.rlim_max = RLIM_INFINITY;
mapcache->max_mcache_size = MCACHE_MAX_SIZE;
} else {
getrlimit(RLIMIT_AS, &rlimit_as);
rlimit_as.rlim_cur = rlimit_as.rlim_max;
if (rlimit_as.rlim_max != RLIM_INFINITY) {
fprintf(stderr, "Warning: QEMU's maximum size of virtual"
" memory is not infinity.\n");
}
if (rlimit_as.rlim_max < MCACHE_MAX_SIZE + NON_MCACHE_MEMORY_SIZE) {
mapcache->max_mcache_size = rlimit_as.rlim_max -
NON_MCACHE_MEMORY_SIZE;
} else {
mapcache->max_mcache_size = MCACHE_MAX_SIZE;
}
}
setrlimit(RLIMIT_AS, &rlimit_as);
mapcache->nr_buckets =
(((mapcache->max_mcache_size >> XC_PAGE_SHIFT) +
(1UL << (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT)) - 1) >>
(MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT));
size = mapcache->nr_buckets * sizeof (MapCacheEntry);
size = (size + XC_PAGE_SIZE - 1) & ~(XC_PAGE_SIZE - 1);
DPRINTF("%s, nr_buckets = %lx size %lu\n", __func__,
mapcache->nr_buckets, size);
mapcache->entry = g_malloc0(size);
}
| 1threat
|
How to make a mobile designed site appear similar on differn't screen resoloutions : <p>I am currently designing a mobile site, that would work perfectly on a 320x480 screen. The issue comes, as newer phones don't use that size anymore, and are much much bigger. (As I found out after I put all that effort in and read it on my phone.) I was wondering if there is any easy way to make it all expand the the proper size I would like it to look without going ahead and giving everything a view-width/vw or view-height/vh rating. (Nvm, I wonder how that would impact the font size.)</p>
<p>Or would I need to go ahead and do that, or something similar? (As it would be particularly bad if it wasn't mobile friendly, for a variety of reasons involving it's creation.)</p>
| 0debug
|
How to reach value in dictionary in list in dictionary in dictionary? : Hello I'm trying to gain the number values from this kind of format:
{'Hello' : {'Values': [{'Number': 2},{'Number': 5}, {'Number':7}]}}
How will this be possible in python? I'm trying to get the output of
[2,5,7].
Thank you very much.
| 0debug
|
javascript replace array of numbers by array of keys : <p>I have this random score (a number) between 0-72.</p>
<p>Each score number has a key number that I have set. (look below)</p>
<p>I need to retrieve the key number by using a function.</p>
<p><strong>Example:</strong></p>
<pre><code>function scoreToKey(score) {
// the mystery code goes here
return PERCENTAGE;
}
scoreToKey(100); // needs to return 100
scoreToKey(72); // needs to return 100
scoreToKey(50); // needs to return 39
scoreToKey(44); // needs to return 4
scoreToKey(29); // needs to return -92
scoreToKey(12); // needs to return -100
scoreToKey(0); // needs to return -100
</code></pre>
<p>I figure you need to use arrays somehow but I can't figure out how.</p>
<p><strong>These are my key values:</strong></p>
<pre><code>score | key
72 100
71 99
70 98
69 97
68 96
67 95
66 94
65 92
64 90
63 87
62 84
61 81
60 78
59 75
58 72
57 69
56 65
55 61
54 57
53 53
52 49
51 44
50 39
49 34
48 28
47 22
46 16
45 10
44 4
43 -2
42 -8
41 -16
40 -24
39 -32
38 -40
37 48
36 56
35 -64
34 -70
33 -76
32 -82
31 -68
30 -90
29 -92
28 -94
27 -96
26 -98
25 -99
1-24 -100
</code></pre>
<p>I would really appreciate your help, I can't figure this out and I also don't know what to search for really.</p>
<p>By the way, your code can be in ES6, I don't mind :) Thanks in advance</p>
| 0debug
|
HTML Remove top space : i dont know why, i have a invisible space in my layout, at the top and i tried to remove it but i doesn't work ...I've already tried margin:0, padding:0, etc...
And this is the css :
* {
margin:0 auto;
padding:0;
border:0;
outline:0;
vertical-align: baseline;
background:#eee;
overflow-x: hidden;
}
header {
width:100vw;
height:300px;
background:red;
}
[Screenshot][1]
[1]: https://i.stack.imgur.com/qsqEY.png
| 0debug
|
How can i different json element with 2 parts in java script : ```
Example json
var json={
list:{
c1:"BTC",
c2:"ETH",
c3:"DOGE",
c4:"LTC",
c5:"BSV",
c6:"XRB",
c7:"SRB",
c8:"WAVE",
c9:"LINK",
c10:"EOS"
}
}
```
**°I want that there is 10 element in this json i want that it can dive this json in 2 part in first part it will show first 5 element and in 2nd part it will show remaining element. So total will be 10 element in 2 parts. How can i do that with java script?**
| 0debug
|
How to get the active tab In Angular Material2 : <p>I want to get which <a href="https://material.angular.io/components/component/tabs" rel="noreferrer">tab</a> is active. I tried to use a <code>@ViewChild</code> decorator and accessing the element properties that way, but it returns <code>null</code>.</p>
<p><strong>Component:</strong></p>
<pre><code>import {Component, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'material-app',
template: `
<md-tab-group #tabGroup>
<md-tab label="Tab 1">Content 1</md-tab>
<md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
`
})
export class AppComponent implements OnInit {
@ViewChild('tabGroup') tabGroup;
constructor() {
}
ngOnInit() {
console.log(this.tabGroup); // MdTabGroup Object
console.log(this.tabGroup.selectedIndex); // null
}
}
</code></pre>
<p><a href="http://plnkr.co/edit/2qjAW8G4FDCkrqVWKeHG?p=preview" rel="noreferrer">Plunker Preview</a></p>
| 0debug
|
SyntaxError in python while using commas : <p><strong>Hi.I am new to python.I caught a syntax error while executing this code:</strong></p>
<pre><code>a="input("Enter a no.")"
print(type(a))
</code></pre>
<p><strong>But if I execute:</strong></p>
<pre><code>a='input("Enter a no.")'
print(type(a))
</code></pre>
<p><strong>Or:</strong></p>
<pre><code>a="input('Enter a no.')"
print(type(a))
</code></pre>
<p><strong>Then no error occurs can someone explain me this.
Thanks in advance.</strong></p>
| 0debug
|
jQuery addEventListener not supported : <p>Simple page with HTML5 video and trying to prevent fast forwarding:</p>
<pre><code> var vid = $("#divVideo");
var suptime = 0;
vid.addEventListener('timeupdate', function(){
if (!vid.seeking){
suptime = vid.currentTime;
}
});
vid.addEventListener('seeking', function(){
var delta = vid.currentTime - suptime;
if (Math.abs(delta) > 0.01) {
vid.currentTime = suptime;
}
});
</code></pre>
<p>In my _Layout page I have:</p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<meta http-equiv="X-UA-Compatible" content="IE=edge;" />
</code></pre>
<p>So I am using everything I have found searching but it still gives me the error. I am using jQuery 3.1.1.</p>
| 0debug
|
Starting point to maintain a website (Test and production enviroment ) with git : <p>Here is the architecture of my project:
<a href="https://i.stack.imgur.com/PURbj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PURbj.png" alt="enter image description here"></a></p>
<p>2 different web servers, one for production environment and other one for test environment ( It contents developer1 folder and developer2 folder).</p>
<p>My question is : Using git how can configure it in order to : </p>
<p>case 1 : </p>
<ul>
<li>Developer 1 can create branch "developer1.b1" based on master on
production side.</li>
<li>He works on it then he merges it to origin/developer1.b1 , </li>
<li>and he can see his changes in developer1.testServerDomain.com</li>
</ul>
<p>case 2 : </p>
<ul>
<li>Developers can push threir branch to origin master</li>
<li>then they can see theirs changes in productionServerDomain.com</li>
</ul>
| 0debug
|
regex / heuristic to detect repetitive junk words like "gfgfgfgf" "dadadada" "sdsdsd" etc : searching for this solution proved to be a bit hard to find, so I'm forced to ask the question.
**First, a bit of a background story:**
- I run a blog
- I have a post about **reCaptcha**
- Sometimes (every week or so) someone tries to be funny and posts spam comments in the similar form to this:
>gfgfgfgf
>sdsdsdsds
>dadadada
You get the idea. Are they testing an automated reCaptcha bypass systems as a proof of concept or just trying to be funny, I don't know and I don't really care (most probably a mix of both).
(edit) Interestingly enough, no other posts are affected by this type of spam comments.
However, thinking about this, it should be relatively simple and easy to detect patterns in the (mostly) single words which those comments have (99%) and prevent those comments from posting. Sounds simple?
But, it must also be good enough to avoid false positives.
If, for example, a comment has single repetitive word like above, then it's definitely a spam.
If, on the other hand, it just has a typo in the middle of the normal sentence, it should pass.
Now, I can already 'hear' comments below why not use Akismet. Or solution X. Or solution Y. Why not external comments system like **Disqus** or **Facebook comments**. Because, I can't. It must be in-house. And I wish to be simple. I already have some things that prevent a lot of junk, but for this particular case they all fail.
**Solution(s) that I have tested so far:**
This is one regex example that is a variant of this answer [here][1], but it's not perfect:
(.+\w)(?=\1+)/gu
**[see live regex101 example][2]**
Problems with it is that in examples below it will pass most of the time, but it will trigger false positives, too:
correct/proper detection:
> 123123123123
> daddaddaddad
> sadsadasad
> sadsadsad
> 121212121
> sasasasasas
> sdsdsdsds
> dsdsdsdsd
> ffffffff
> blahblah
> ioiooioioioi
> popopopopop
> Hi I dont think this is a spam.
improper/incorrect detection (false positive):
> I loooovve this. It's awesooooommeee!
Now, this is tricky. The filter does exactly what it was instructed to do, however, "ooovv" and "oooommeee" patterns are not exactly repetitive in the same sense like the first ones listed above ("gfgfgfgf" etc.) - filter detect "oo" pattern repetition. Yes, it is correct, but not exactly what I want to target.
Does anyone have an idea how can I improve this regex detection to be smarter a bit?
One thought / idea that I have is outside of the regex itself, and that is to let pass single repetitions IF comment contains more than 1 word (e.g. something closer to a full sentence). But, I'd like the case where actual repetition can be differentiated, such as in the case of "awesoooommeee" word.
Thanks!
[1]: https://stackoverflow.com/a/943924/2715309
[2]: https://regex101.com/r/6k0Fiz/1
| 0debug
|
C++ error, compiler won't recognize string::push_back : <p>The function it has an issue with:</p>
<pre><code>string encode (string message, string key) {
string code = "whatever";
string forst;
int num;
string::size_type begin = 0;
message = lower_and_strip(message);
for (char val : message) {
num = return_encoded_char(key, begin, val);
forst = to_string(num);
code.push_back(forst); //*******************************
}
return code;
}
</code></pre>
<p>The starred line is what it points to. The return_encoded_char function returns an integer. </p>
<p>The specific error is
<code>proj05.cpp:68:23: error: no matching function for call to 'std::basic_string<char>::push_back(std::string&)'</code> and points to the line I starred.</p>
<p>I initially just declared <code>code</code> without initializing it, but changing that didn't fix it. All the similar questions I could find had some other element to blame; I feel like this should be relatively straightforward, though obviously it's not since it isn't working. </p>
<p>I have <code>#include <stream></code> and <code>using std::to_string</code> etc. I'm using -std=c++11 to compile it.</p>
<p>Help.</p>
<p>P.S. Using Geany on Linux.</p>
| 0debug
|
Unsupported field: Year when formatting an instant to Date ISO : <p>I am trying to format an Instant to a ldap date ISO8601 but it fails at f.format(Instant.now()); :</p>
<pre><code>String input = "20161012235959.0Z";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuuMMddHHmmss[,S][.S]X" );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
Instant instant = odt.toInstant ();
f.format(Instant.now());
</code></pre>
<p>And the error is :</p>
<pre><code>java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
at java.time.Instant.getLong(Instant.java:603)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
...
...
</code></pre>
| 0debug
|
Easiest way of building up visual representation of a graph data structure : <p>I need some suggestions for a libraries or other tools that I can use. I have a graph data structure built up of class objects each having its children (again objects of the class) in a list variable. I need a quick and easy way to draw these nodes, color them or change the shape of the nodes depending upon various conditions for visualization and proof of concept purposes. Since this is not the primary motive of the program and something that needs to be on the side, it doesn't matter if its an ugly method, it just needs to be hassle free. I have conisdered using graphviz for this but would be open to suggestions as I may have to make changes to the color/shape of the nodes while traversing the tree again and again.</p>
| 0debug
|
Divide the Bonus : <p>I have a list (array) of employees who will be rewarded as follows:</p>
<ul>
<li><p>Const worker = [
<code>{name: "John", prize: 1000, prioritize: 1},</code>
<code>{name: "Andy", prize: 2000, prioritize: 2},</code>
<code>{name: "Bill", prize: 2200, prioritize: 3},</code>
<code>{name: :Carry", prize: 3100, prioritize: 4},</code>
<code>{name: "Asawa", prize: 4000, prioritize: 5}</code>
]; //( array Worker is not fixed ...)</p></li>
<li><p>Let TotalPrize = 7100 // fund bonus</p></li>
</ul>
<p>Problem: I want to subtract TotalPrize for the list above (1-> 2-> 3 ...) so that Workers gets the full prize by order Prioritize:</p>
<ul>
<li>John: 1000 (full)</li>
<li>Andy: 2000 (full)</li>
<li>Bill: 2200 (full)</li>
<li>Carry: 1900 (the list above, Carry must be 3100, but because TotalPrize = 7100 has been divided in advance for the first three remaining 1900)</li>
<li>Asawa: 0 (because all the money for the first 4 people was divided)</li>
</ul>
<p>Who has the solution and helps me to solve the problem, 2 weeks in desperation. So sad</p>
| 0debug
|
PLEASE HELP!! Page refreshes when I click Register! (I'm new to HTML) : My friends are counting on me to make a good rpg game, I'm almost done, but this problem occurs ----> For some reason when I click 'Register' page refreshes..? I copied this register code by the way.. so that could be the problem? please help ! :(
input type='hidden' name='referer' value=''>
input type="submit" name="submit" value="Register" class="button"/>
this is the code, please..anyone
| 0debug
|
static inline void dxt3_block_internal(uint8_t *dst, ptrdiff_t stride,
const uint8_t *block)
{
int x, y;
uint32_t colors[4];
uint16_t color0 = AV_RL16(block + 8);
uint16_t color1 = AV_RL16(block + 10);
uint32_t code = AV_RL32(block + 12);
extract_color(colors, color0, color1, 1, 0);
for (y = 0; y < 4; y++) {
const uint16_t alpha_code = AV_RL16(block + 2 * y);
uint8_t alpha_values[4];
alpha_values[0] = ((alpha_code >> 0) & 0x0F) * 17;
alpha_values[1] = ((alpha_code >> 4) & 0x0F) * 17;
alpha_values[2] = ((alpha_code >> 8) & 0x0F) * 17;
alpha_values[3] = ((alpha_code >> 12) & 0x0F) * 17;
for (x = 0; x < 4; x++) {
uint8_t alpha = alpha_values[x];
uint32_t pixel = colors[code & 3] | (alpha << 24);
code >>= 2;
AV_WL32(dst + x * 4, pixel);
}
dst += stride;
}
}
| 1threat
|
no errors but still app force closes in android studio : <p>I am trying to make an app to take an image when the button is clicked and then take that image and place it in the image view field.
The given code is fine with no errors, i have checked many times. Still i get this error of runtime exception even when i have instanciated the activity in the manifest file.</p>
<p>here is xml code:</p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
tools:context="com.example.android.tryingcamera.MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="9"/>
<Button
android:id="@+id/btnCamera"
android:layout_weight="1"
android:text="Tap To Open Camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btncameraClicked"/>
</code></pre>
<p></p>
<p>here is java code:</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private ImageView imageview=(ImageView)findViewById(R.id.imageView);
private Button btncamera = (Button) findViewById(R.id.btnCamera);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btncameraClicked(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data ){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap=(Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
</code></pre>
<p>}</p>
<p>The logcat show this:</p>
<pre><code>Process: com.example.android.tryingcamera, PID: 27769
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.tryingcamera/com.example.android.tryingcamera.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.android.tryingcamera.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code></pre>
| 0debug
|
How do I select hardware OpenGL rendering for MATLAB on Linux : <p>When I start matlab on my linux machine, I get the notice, "MATLAB is selecting SOFTWARE OPENGL rendering." Once it starts up, if I try <code>opengl hardware</code> I get the message that I can't switch at runtime. How do I enable hardware rendering as simply as possible?</p>
| 0debug
|
static uint64_t pl061_read(void *opaque, hwaddr offset,
unsigned size)
{
PL061State *s = (PL061State *)opaque;
if (offset >= 0xfd0 && offset < 0x1000) {
return s->id[(offset - 0xfd0) >> 2];
}
if (offset < 0x400) {
return s->data & (offset >> 2);
}
switch (offset) {
case 0x400:
return s->dir;
case 0x404:
return s->isense;
case 0x408:
return s->ibe;
case 0x40c:
return s->iev;
case 0x410:
return s->im;
case 0x414:
return s->istate;
case 0x418:
return s->istate & s->im;
case 0x420:
return s->afsel;
case 0x500:
return s->dr2r;
case 0x504:
return s->dr4r;
case 0x508:
return s->dr8r;
case 0x50c:
return s->odr;
case 0x510:
return s->pur;
case 0x514:
return s->pdr;
case 0x518:
return s->slr;
case 0x51c:
return s->den;
case 0x520:
return s->locked;
case 0x524:
return s->cr;
case 0x528:
return s->amsel;
default:
qemu_log_mask(LOG_GUEST_ERROR,
"pl061_read: Bad offset %x\n", (int)offset);
return 0;
}
}
| 1threat
|
PHP: IF() Euqal TO Not working : `if($_SESSION['auth'] != 2 || $_SESSION['auth'] != 3){
header("location:../login/login.php");
}`
what am i doing wrong, ist keep sending me back,
ist only when session is 1 or not set, it should send me back
best regrads kevin
| 0debug
|
Remove n number of dot(.) from String in Java : <p>I have the following string and I want to remove dynamic number of dot(.) at the end of the String.</p>
<pre><code>"abc....."
</code></pre>
<p><strong>Dot(.) can be more than one</strong></p>
| 0debug
|
static int decode_subpacket(COOKContext *q, uint8_t *inbuffer,
int sub_packet_size, int16_t *outbuffer) {
int i,j;
int value;
float* tmp_ptr;
decode_bytes(inbuffer, q->decoded_bytes_buffer, sub_packet_size);
init_get_bits(&q->gb, q->decoded_bytes_buffer, sub_packet_size*8);
decode_gain_info(&q->gb, &q->gain_current);
memcpy(&q->gain_copy, &q->gain_current ,sizeof(COOKgain));
if(q->nb_channels==2 && q->joint_stereo==1){
joint_decode(q, q->decode_buf_ptr[0], q->decode_buf_ptr[2]);
tmp_ptr = q->decode_buf_ptr[1];
q->decode_buf_ptr[1] = q->decode_buf_ptr[0];
q->decode_buf_ptr[0] = tmp_ptr;
tmp_ptr = q->decode_buf_ptr[3];
q->decode_buf_ptr[3] = q->decode_buf_ptr[2];
q->decode_buf_ptr[2] = tmp_ptr;
q->gain_now_ptr = &q->gain_now;
q->gain_previous_ptr = &q->gain_previous;
for (i=0 ; i<q->nb_channels ; i++){
cook_imlt(q, q->decode_buf_ptr[i*2], q->mono_mdct_output, q->mlt_tmp);
gain_compensate(q, q->mono_mdct_output, q->gain_now_ptr,
q->gain_previous_ptr, q->previous_buffer_ptr[0]);
tmp_ptr = q->previous_buffer_ptr[0];
q->previous_buffer_ptr[0] = q->previous_buffer_ptr[1];
q->previous_buffer_ptr[1] = tmp_ptr;
for (j=0 ; j<q->samples_per_frame ; j++){
value = lrintf(q->mono_mdct_output[j]);
if(value < -32768) value = -32768;
else if(value > 32767) value = 32767;
outbuffer[2*j+i] = value;
}
}
memcpy(&q->gain_now, &q->gain_previous, sizeof(COOKgain));
memcpy(&q->gain_previous, &q->gain_current, sizeof(COOKgain));
} else if (q->nb_channels==2 && q->joint_stereo==0) {
mono_decode(q, q->decode_buf_ptr[0]);
tmp_ptr = q->decode_buf_ptr[0];
q->decode_buf_ptr[0] = q->decode_buf_ptr[1];
q->decode_buf_ptr[1] = q->decode_buf_ptr[2];
q->decode_buf_ptr[2] = q->decode_buf_ptr[3];
q->decode_buf_ptr[3] = tmp_ptr;
q->gain_now_ptr = &q->gain_now;
q->gain_previous_ptr = &q->gain_previous;
cook_imlt(q, q->decode_buf_ptr[0], q->mono_mdct_output,q->mlt_tmp);
gain_compensate(q, q->mono_mdct_output, q->gain_now_ptr,
q->gain_previous_ptr, q->previous_buffer_ptr[0]);
tmp_ptr = q->previous_buffer_ptr[0];
q->previous_buffer_ptr[0] = q->previous_buffer_ptr[1];
q->previous_buffer_ptr[1] = tmp_ptr;
for (j=0 ; j<q->samples_per_frame ; j++){
value = lrintf(q->mono_mdct_output[j]);
if(value < -32768) value = -32768;
else if(value > 32767) value = 32767;
outbuffer[2*j+1] = value;
}
init_get_bits(&q->gb, q->decoded_bytes_buffer, sub_packet_size*8+q->bits_per_subpacket);
decode_gain_info(&q->gb, &q->gain_current);
mono_decode(q, q->decode_buf_ptr[0]);
tmp_ptr = q->decode_buf_ptr[0];
q->decode_buf_ptr[1] = q->decode_buf_ptr[2];
q->decode_buf_ptr[2] = q->decode_buf_ptr[3];
q->decode_buf_ptr[3] = tmp_ptr;
q->gain_now_ptr = &q->gain_now;
q->gain_previous_ptr = &q->gain_previous;
cook_imlt(q, q->decode_buf_ptr[0], q->mono_mdct_output,q->mlt_tmp);
gain_compensate(q, q->mono_mdct_output, q->gain_now_ptr, q->gain_previous_ptr, q->previous_buffer_ptr[0]);
tmp_ptr = q->previous_buffer_ptr[0];
q->previous_buffer_ptr[0] = q->previous_buffer_ptr[1];
q->previous_buffer_ptr[1] = tmp_ptr;
for (j=0 ; j<q->samples_per_frame ; j++){
value = lrintf(q->mono_mdct_output[j]);
if(value < -32768) value = -32768;
else if(value > 32767) value = 32767;
outbuffer[2*j] = value;
}
memcpy(&q->gain_now, &q->gain_previous, sizeof(COOKgain));
memcpy(&q->gain_previous, &q->gain_current, sizeof(COOKgain));
} else {
mono_decode(q, q->decode_buf_ptr[0]);
tmp_ptr = q->decode_buf_ptr[1];
q->decode_buf_ptr[1] = q->decode_buf_ptr[0];
q->decode_buf_ptr[0] = tmp_ptr;
q->gain_now_ptr = &q->gain_now;
q->gain_previous_ptr = &q->gain_previous;
cook_imlt(q, q->decode_buf_ptr[0], q->mono_mdct_output,q->mlt_tmp);
gain_compensate(q, q->mono_mdct_output, q->gain_now_ptr,
q->gain_previous_ptr, q->mono_previous_buffer1);
for (j=0 ; j<q->samples_per_frame ; j++){
value = lrintf(q->mono_mdct_output[j]);
if(value < -32768) value = -32768;
else if(value > 32767) value = 32767;
outbuffer[j] = value;
}
memcpy(&q->gain_now, &q->gain_previous, sizeof(COOKgain));
memcpy(&q->gain_previous, &q->gain_current, sizeof(COOKgain));
}
return q->samples_per_frame * sizeof(int16_t);
}
| 1threat
|
Quickest way to turn off the delete option in swipe to delete in Xcode 8 : Hello fellow programmers, I know all about the swipe to delete with table view function, but what would be the easiest way to have an image view simply swipe to delete with the delete option not opening on the side, but simply deleting right away. I have done some looking but I can't find a good answer, thanks for the help.
| 0debug
|
static void tcg_out_qemu_ld (TCGContext *s, const TCGArg *args, int opc)
{
int addr_reg, data_reg, data_reg2, r0, r1, rbase, mem_index, s_bits, bswap;
#ifdef CONFIG_SOFTMMU
int r2;
void *label1_ptr, *label2_ptr;
#endif
#if TARGET_LONG_BITS == 64
int addr_reg2;
#endif
data_reg = *args++;
if (opc == 3)
data_reg2 = *args++;
else
data_reg2 = 0;
addr_reg = *args++;
#if TARGET_LONG_BITS == 64
addr_reg2 = *args++;
#endif
mem_index = *args;
s_bits = opc & 3;
#ifdef CONFIG_SOFTMMU
r0 = 3;
r1 = 4;
r2 = 0;
rbase = 0;
tcg_out32 (s, (RLWINM
| RA (r0)
| RS (addr_reg)
| SH (32 - (TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS))
| MB (32 - (CPU_TLB_BITS + CPU_TLB_ENTRY_BITS))
| ME (31 - CPU_TLB_ENTRY_BITS)
)
);
tcg_out32 (s, ADD | RT (r0) | RA (r0) | RB (TCG_AREG0));
tcg_out32 (s, (LWZU
| RT (r1)
| RA (r0)
| offsetof (CPUState, tlb_table[mem_index][0].addr_read)
)
);
tcg_out32 (s, (RLWINM
| RA (r2)
| RS (addr_reg)
| SH (0)
| MB ((32 - s_bits) & 31)
| ME (31 - TARGET_PAGE_BITS)
)
);
tcg_out32 (s, CMP | BF (7) | RA (r2) | RB (r1));
#if TARGET_LONG_BITS == 64
tcg_out32 (s, LWZ | RT (r1) | RA (r0) | 4);
tcg_out32 (s, CMP | BF (6) | RA (addr_reg2) | RB (r1));
tcg_out32 (s, CRAND | BT (7, CR_EQ) | BA (6, CR_EQ) | BB (7, CR_EQ));
#endif
label1_ptr = s->code_ptr;
#ifdef FAST_PATH
tcg_out32 (s, BC | BI (7, CR_EQ) | BO_COND_TRUE);
#endif
#if TARGET_LONG_BITS == 32
tcg_out_mov (s, 3, addr_reg);
tcg_out_movi (s, TCG_TYPE_I32, 4, mem_index);
#else
tcg_out_mov (s, 3, addr_reg2);
tcg_out_mov (s, 4, addr_reg);
tcg_out_movi (s, TCG_TYPE_I32, 5, mem_index);
#endif
tcg_out_call (s, (tcg_target_long) qemu_ld_helpers[s_bits], 1);
switch (opc) {
case 0|4:
tcg_out32 (s, EXTSB | RA (data_reg) | RS (3));
break;
case 1|4:
tcg_out32 (s, EXTSH | RA (data_reg) | RS (3));
break;
case 0:
case 1:
case 2:
if (data_reg != 3)
tcg_out_mov (s, data_reg, 3);
break;
case 3:
if (data_reg == 3) {
if (data_reg2 == 4) {
tcg_out_mov (s, 0, 4);
tcg_out_mov (s, 4, 3);
tcg_out_mov (s, 3, 0);
}
else {
tcg_out_mov (s, data_reg2, 3);
tcg_out_mov (s, 3, 4);
}
}
else {
if (data_reg != 4) tcg_out_mov (s, data_reg, 4);
if (data_reg2 != 3) tcg_out_mov (s, data_reg2, 3);
}
break;
}
label2_ptr = s->code_ptr;
tcg_out32 (s, B);
#ifdef FAST_PATH
reloc_pc14 (label1_ptr, (tcg_target_long) s->code_ptr);
#endif
tcg_out32 (s, (LWZ
| RT (r0)
| RA (r0)
| (ADDEND_OFFSET + offsetof (CPUTLBEntry, addend)
- offsetof (CPUTLBEntry, addr_read))
));
tcg_out32 (s, ADD | RT (r0) | RA (r0) | RB (addr_reg));
#else
r0 = addr_reg;
r1 = 3;
rbase = GUEST_BASE ? TCG_GUEST_BASE_REG : 0;
#endif
#ifdef TARGET_WORDS_BIGENDIAN
bswap = 0;
#else
bswap = 1;
#endif
switch (opc) {
default:
case 0:
tcg_out32 (s, LBZX | TAB (data_reg, rbase, r0));
break;
case 0|4:
tcg_out32 (s, LBZX | TAB (data_reg, rbase, r0));
tcg_out32 (s, EXTSB | RA (data_reg) | RS (data_reg));
break;
case 1:
if (bswap)
tcg_out32 (s, LHBRX | TAB (data_reg, rbase, r0));
else
tcg_out32 (s, LHZX | TAB (data_reg, rbase, r0));
break;
case 1|4:
if (bswap) {
tcg_out32 (s, LHBRX | TAB (data_reg, rbase, r0));
tcg_out32 (s, EXTSH | RA (data_reg) | RS (data_reg));
}
else tcg_out32 (s, LHAX | TAB (data_reg, rbase, r0));
break;
case 2:
if (bswap)
tcg_out32 (s, LWBRX | TAB (data_reg, rbase, r0));
else
tcg_out32 (s, LWZX | TAB (data_reg, rbase, r0));
break;
case 3:
if (bswap) {
tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);
tcg_out32 (s, LWBRX | TAB (data_reg, rbase, r0));
tcg_out32 (s, LWBRX | TAB (data_reg2, rbase, r1));
}
else {
#ifdef CONFIG_USE_GUEST_BASE
tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);
tcg_out32 (s, LWZX | TAB (data_reg2, rbase, r0));
tcg_out32 (s, LWZX | TAB (data_reg, rbase, r1));
#else
if (r0 == data_reg2) {
tcg_out32 (s, LWZ | RT (0) | RA (r0));
tcg_out32 (s, LWZ | RT (data_reg) | RA (r0) | 4);
tcg_out_mov (s, data_reg2, 0);
}
else {
tcg_out32 (s, LWZ | RT (data_reg2) | RA (r0));
tcg_out32 (s, LWZ | RT (data_reg) | RA (r0) | 4);
}
#endif
}
break;
}
#ifdef CONFIG_SOFTMMU
reloc_pc24 (label2_ptr, (tcg_target_long) s->code_ptr);
#endif
}
| 1threat
|
TensorFlow: How to ensure Tensors are in the same graph : <p>I'm trying to get started with TensorFlow in python, building a simple feed-forward NN. I have one class that holds the network weights (variables that are updated during train, and are supposed to remain constant for runtime) and another script to train the network, which gets the training data, separates them to batches and trains the network in batches.
When I try to train the network, I get an error indicating that the data tensor is not in the same graph as the NN tensors:</p>
<blockquote>
<p>ValueError: Tensor("Placeholder:0", shape=(10, 5), dtype=float32) must be from the same graph as Tensor("windows/embedding/Cast:0", shape=(100232, 50), dtype=float32).</p>
</blockquote>
<p>The relevant parts in the training script are:</p>
<pre><code>def placeholder_inputs(batch_size, ner):
windows_placeholder = tf.placeholder(tf.float32, shape=(batch_size, ner.windowsize))
labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
return windows_placeholder, labels_placeholder
with tf.Session() as sess:
windows_placeholder, labels_placeholder = placeholder_inputs(batch_size, ner)
logits = ner.inference(windows_placeholder)
</code></pre>
<p>And the relevant in the network class are:</p>
<pre><code>class WindowNER(object):
def __init__(self, wv, windowsize=3, dims=[None, 100,5], reg=0.01):
self.reg=reg
self.windowsize=windowsize
self.vocab_size = wv.shape[0]
self.embedding_dim = wv.shape[1]
with tf.name_scope("embedding"):
self.L = tf.cast(tf.Variable(wv, trainable=True, name="L"), tf.float32)
with tf.name_scope('hidden1'):
self.W = tf.Variable(tf.truncated_normal([windowsize * self.embedding_dim, dims[1]],
stddev=1.0 / math.sqrt(float(windowsize*self.embedding_dim))),
name='weights')
self.b1 = tf.Variable(tf.zeros([dims[1]]), name='biases')
with tf.name_scope('output'):
self.U = tf.Variable(tf.truncated_normal([dims[1], dims[2]], stddev = 1.0 / math.sqrt(float(dims[1]))), name='weights')
self.b2 = tf.Variable(tf.zeros(dims[2], name='biases'))
def inference(self, windows):
with tf.name_scope("embedding"):
embedded_words = tf.reshape(tf.nn.embedding_lookup(self.L, windows), [windows.get_shape()[0], self.windowsize * self.embedding_dim])
with tf.name_scope("hidden1"):
h = tf.nn.tanh(tf.matmul(embedded_words, self.W) + self.b1)
with tf.name_scope('output'):
t = tf.matmul(h, self.U) + self.b2
</code></pre>
<p>Why are there two graphs in the first place, and how can I ensure that data placeholder tensors are in the same graph as the NN?</p>
<p>Thanks!!</p>
| 0debug
|
Unable to find specific value from array with indexof method : Below is my array :
$scope.Statistics = [];
This statistics array contains records like below :
['Usa'] : regions:
[0] : name : 'chicago'
[1] : name : 'miami'
[2] : name : 'alaska'
[3] : name : 'washington'
This is my loop :
<tr ng-repeat="region in Statistics[currentRegion].regions">
<a data-ng-click="Myfunc(region.name)">
</a>
</tr>
$scope.currentRegion = 'Usa';
$scope.Myfunc = function (region) {
$scope.currentIndex = $scope.Statistics[$scope.currentRegion].regions.indexOf(region);
console.log($scope.currentIndex); // -1
}
> The indexOf() method returns the first index at which a given element
> can be found in the array, or -1 if it is not present.
So can anybody please help me me how do i find respective region from this statistics array??
| 0debug
|
String moving an alphabet after the next alphabet : String input = ``Chit Nyein Oo is nothing.´´;
output =``Chti Nyeni Oo si nothnig.´´
I want to move each` i ´ after the next alphabet of its. How can I do that? Please.
| 0debug
|
show/hide a div with drop dwon value in asp.net : its my code i want to hide div which have id selnumber (when i select form 60/61 and show a text message "It is form 60/61" at the place of div) but when select pan then show the div.
<div id="selpan">
<asp:DropDownList ID="ddlpan" runat="server">
<asp:ListItem>---Select---</asp:ListItem>
<asp:ListItem>PAN</asp:ListItem>
<asp:ListItem>FORM 60/61</asp:ListItem>
</asp:DropDownList> </div>
</td><div id="selnumber">
<td colspan="3">
<asp:Label ID="add_no" runat="server" Font-Bold="True" Font-Names="Verdana"
Font-Size="10pt" Font-Strikeout="False" Text="File Number"></asp:Label>
</td><td>
<asp:TextBox ID="tbnumber" runat="server" ontextchanged="tbnumber_TextChanged"></asp:TextBox>
</td>
</div>
| 0debug
|
static int tak_read_header(AVFormatContext *s)
{
TAKDemuxContext *tc = s->priv_data;
AVIOContext *pb = s->pb;
GetBitContext gb;
AVStream *st;
uint8_t *buffer = NULL;
int ret;
st = avformat_new_stream(s, 0);
if (!st)
return AVERROR(ENOMEM);
st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
st->codec->codec_id = AV_CODEC_ID_TAK;
st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
tc->mlast_frame = 0;
if (avio_rl32(pb) != MKTAG('t', 'B', 'a', 'K')) {
avio_seek(pb, -4, SEEK_CUR);
return 0;
}
while (!url_feof(pb)) {
enum TAKMetaDataType type;
int size;
type = avio_r8(pb) & 0x7f;
size = avio_rl24(pb);
switch (type) {
case TAK_METADATA_STREAMINFO:
case TAK_METADATA_LAST_FRAME:
case TAK_METADATA_ENCODER:
buffer = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!buffer)
return AVERROR(ENOMEM);
if (avio_read(pb, buffer, size) != size) {
av_freep(&buffer);
return AVERROR(EIO);
}
init_get_bits(&gb, buffer, size * 8);
break;
case TAK_METADATA_MD5: {
uint8_t md5[16];
int i;
if (size != 19)
return AVERROR_INVALIDDATA;
avio_read(pb, md5, 16);
avio_skip(pb, 3);
av_log(s, AV_LOG_VERBOSE, "MD5=");
for (i = 0; i < 16; i++)
av_log(s, AV_LOG_VERBOSE, "%02x", md5[i]);
av_log(s, AV_LOG_VERBOSE, "\n");
break;
}
case TAK_METADATA_END: {
int64_t curpos = avio_tell(pb);
if (pb->seekable) {
ff_ape_parse_tag(s);
avio_seek(pb, curpos, SEEK_SET);
}
tc->data_end += curpos;
return 0;
}
default:
ret = avio_skip(pb, size);
if (ret < 0)
return ret;
}
if (type == TAK_METADATA_STREAMINFO) {
TAKStreamInfo ti;
avpriv_tak_parse_streaminfo(&gb, &ti);
if (ti.samples > 0)
st->duration = ti.samples;
st->codec->bits_per_coded_sample = ti.bps;
if (ti.ch_layout)
st->codec->channel_layout = ti.ch_layout;
st->codec->sample_rate = ti.sample_rate;
st->codec->channels = ti.channels;
st->start_time = 0;
avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
st->codec->extradata = buffer;
st->codec->extradata_size = size;
buffer = NULL;
} else if (type == TAK_METADATA_LAST_FRAME) {
if (size != 11)
return AVERROR_INVALIDDATA;
tc->mlast_frame = 1;
tc->data_end = get_bits64(&gb, TAK_LAST_FRAME_POS_BITS) +
get_bits(&gb, TAK_LAST_FRAME_SIZE_BITS);
av_freep(&buffer);
} else if (type == TAK_METADATA_ENCODER) {
av_log(s, AV_LOG_VERBOSE, "encoder version: %0X\n",
get_bits_long(&gb, TAK_ENCODER_VERSION_BITS));
av_freep(&buffer);
}
}
return AVERROR_EOF;
}
| 1threat
|
Find PinCode in file of various letters/numbers : <p><strong><em>Given a file of seemingly meaningless letters called “data.txt”, write a function findPin(inFile) that returns a four-number pin code within file. (All other characters are letters except for the pin code)</em></strong></p>
<p>I know I'm supposed to open the data file and then iterate through it until I come across a number, but I'm not sure how to go about doing this. The data.txt file is...</p>
<pre><code>loremipsumdolorsitametconsecteturadipiscingelit
seddoeiusmodtemporincididuntutlaboreetdoloremag
naaliquautenimadminimveniamquisnostrudexercitat
ionullamcolaborisnisiutaliquipexeacommodoconseq
uatduisauteiruredolorinrepre7269henderitinvolup
tatevelitessecillumdoloreeufugiatnullapariature
xcepteursintoccaecatcupidatatnonproidentsuntinc
ulpaquiofficiadeseruntmollitanimidestlaborumqwe
</code></pre>
<p>So obviously the pin number is 7269, but I need helping getting there. Sorry I'm just a beginner in python and this is really tripping me up.</p>
| 0debug
|
Chrome - Debug Angular/Typescript - how to navigate to ts file : <p>To debug my angular front end, I open the dev tools in Chrome and the sources tab and navigate to the ts file by clicking down through all the folders and when I do find the ts file, I then set a breakpoint. and go back to using the application and then start debugging.</p>
<p>While this works, it is time consuming to have to drill down through folders... and look for the ts file. As the project has grown, I find it is becoming even more time consuming.</p>
<p>I also have to remember which TS file is associated with which page.</p>
<p>Does anyone know if it is possible to go directly from the page to the ts file ?</p>
<p>I would love to be able to right click and select a menu item to go directly to the ts file in exactly the way Inspect works for HTML files.</p>
<p>Any suggestions should consider that the project is quite large.
I did try to use some add-on but it took ages to refresh was unusable.</p>
<p>Does anyone have any tips on how to avoid drilling down through the folders to find the ts file and setting the breakpoint. How can this be achieved in a much faster, efficient way ?</p>
<p>Thanks a million,
Fergal.</p>
| 0debug
|
"The breakpoint will not currently be hit. A copy of file was found in dll file, but the current source code is different" : <p>I keep getting this error saying there's a copy of the .cs file hence the break point will not get hit. </p>
<p>I have tried cleaning solution, rebuilding , deleting the .pdb files in the obj and bin folders, closing VS and restarting it, restarting the whole machine (It's Windows! Sometimes the most complicated, unexplained problems get fixed like this :\ )</p>
<p>Any idea what else I can try? it's a .net project on VS2015</p>
<p><a href="https://i.stack.imgur.com/pLjAW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pLjAW.png" alt="Breakpoint error "></a></p>
| 0debug
|
static void detach(sPAPRDRConnector *drc, DeviceState *d,
spapr_drc_detach_cb *detach_cb,
void *detach_cb_opaque, Error **errp)
{
DPRINTFN("drc: %x, detach", get_index(drc));
drc->detach_cb = detach_cb;
drc->detach_cb_opaque = detach_cb_opaque;
if (!drc->signalled && !drc->configured) {
drc->isolation_state = SPAPR_DR_ISOLATION_STATE_ISOLATED;
if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {
DPRINTFN("awaiting transition to isolated state before removal");
if (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI &&
drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {
DPRINTFN("awaiting transition to unusable state before removal");
drc->indicator_state = SPAPR_DR_INDICATOR_STATE_INACTIVE;
if (drc->detach_cb) {
drc->detach_cb(drc->dev, drc->detach_cb_opaque);
drc->awaiting_release = false;
g_free(drc->fdt);
drc->fdt = NULL;
drc->fdt_start_offset = 0;
object_property_del(OBJECT(drc), "device", NULL);
drc->dev = NULL;
drc->detach_cb = NULL;
drc->detach_cb_opaque = NULL;
| 1threat
|
How to select all data from these two tables? : <p><a href="https://i.stack.imgur.com/28YKn.png" rel="nofollow noreferrer">Order Table</a></p>
<p><a href="https://i.stack.imgur.com/Z3z3z.png" rel="nofollow noreferrer">Product Table</a></p>
<p>I need to select all from these two tables. Is it possible?</p>
| 0debug
|
R.java file cannot be resolved in application in android studio. Give me suggestions that what are the things I should check for this issue. : <p>R.java file cannot be resolved in application in android studio. Give me suggestions that what are the things I should check for this issue. Thank you for advance.</p>
| 0debug
|
static int scsi_disk_emulate_mode_sense(SCSIRequest *req, uint8_t *outbuf)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
uint64_t nb_sectors;
int page, dbd, buflen;
uint8_t *p;
uint8_t dev_specific_param;
dbd = req->cmd.buf[1] & 0x8;
page = req->cmd.buf[2] & 0x3f;
DPRINTF("Mode Sense (page %d, len %zd)\n", page, req->cmd.xfer);
memset(outbuf, 0, req->cmd.xfer);
p = outbuf;
if (bdrv_is_read_only(s->bs)) {
dev_specific_param = 0x80;
} else {
dev_specific_param = 0x00;
}
if (req->cmd.buf[0] == MODE_SENSE) {
p[1] = 0;
p[2] = dev_specific_param;
p[3] = 0;
p += 4;
} else {
p[2] = 0;
p[3] = dev_specific_param;
p[6] = p[7] = 0;
p += 8;
}
bdrv_get_geometry(s->bs, &nb_sectors);
if ((~dbd) & nb_sectors) {
if (req->cmd.buf[0] == MODE_SENSE) {
outbuf[3] = 8;
} else {
outbuf[7] = 8;
}
nb_sectors /= s->cluster_size;
nb_sectors--;
if (nb_sectors > 0xffffff)
nb_sectors = 0xffffff;
p[0] = 0;
p[1] = (nb_sectors >> 16) & 0xff;
p[2] = (nb_sectors >> 8) & 0xff;
p[3] = nb_sectors & 0xff;
p[4] = 0;
p[5] = 0;
p[6] = s->cluster_size * 2;
p[7] = 0;
p += 8;
}
switch (page) {
case 0x04:
case 0x05:
case 0x08:
case 0x2a:
p += mode_sense_page(req, page, p);
break;
case 0x3f:
p += mode_sense_page(req, 0x08, p);
p += mode_sense_page(req, 0x2a, p);
break;
}
buflen = p - outbuf;
if (req->cmd.buf[0] == MODE_SENSE) {
outbuf[0] = buflen - 1;
} else {
outbuf[0] = ((buflen - 2) >> 8) & 0xff;
outbuf[1] = (buflen - 2) & 0xff;
}
if (buflen > req->cmd.xfer)
buflen = req->cmd.xfer;
return buflen;
}
| 1threat
|
static int mpegps_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
AVStream *st;
int len, startcode, i, type, codec_id;
int64_t pts, dts;
redo:
len = mpegps_read_pes_header(s, NULL, &startcode, &pts, &dts, 1);
if (len < 0)
return len;
for(i=0;i<s->nb_streams;i++) {
st = s->streams[i];
if (st->id == startcode)
goto found;
}
if (startcode >= 0x1e0 && startcode <= 0x1ef) {
type = CODEC_TYPE_VIDEO;
codec_id = CODEC_ID_MPEG2VIDEO;
} else if (startcode >= 0x1c0 && startcode <= 0x1df) {
type = CODEC_TYPE_AUDIO;
codec_id = CODEC_ID_MP2;
} else if (startcode >= 0x80 && startcode <= 0x9f) {
type = CODEC_TYPE_AUDIO;
codec_id = CODEC_ID_AC3;
} else if (startcode >= 0xa0 && startcode <= 0xbf) {
type = CODEC_TYPE_AUDIO;
codec_id = CODEC_ID_PCM_S16BE;
} else {
skip:
url_fskip(&s->pb, len);
goto redo;
}
st = av_new_stream(s, startcode);
if (!st)
goto skip;
st->codec.codec_type = type;
st->codec.codec_id = codec_id;
if (codec_id != CODEC_ID_PCM_S16BE)
st->need_parsing = 1;
found:
if (startcode >= 0xa0 && startcode <= 0xbf) {
int b1, freq;
if (len <= 3)
goto skip;
get_byte(&s->pb);
b1 = get_byte(&s->pb);
get_byte(&s->pb);
len -= 3;
freq = (b1 >> 4) & 3;
st->codec.sample_rate = lpcm_freq_tab[freq];
st->codec.channels = 1 + (b1 & 7);
st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;
}
av_new_packet(pkt, len);
get_buffer(&s->pb, pkt->data, pkt->size);
pkt->pts = pts;
pkt->dts = dts;
pkt->stream_index = st->index;
#if 0
printf("%d: pts=%0.3f dts=%0.3f\n",
pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0);
#endif
return 0;
}
| 1threat
|
static CPAccessResult ats_access(CPUARMState *env, const ARMCPRegInfo *ri)
{
if (ri->opc2 & 4) {
return CP_ACCESS_TRAP_UNCATEGORIZED;
}
return CP_ACCESS_OK;
}
| 1threat
|
static int xan_decode_frame(AVCodecContext *avctx,
void *data, int *data_size,
AVPacket *avpkt)
{
XanContext *s = avctx->priv_data;
int ftype;
int ret;
s->pic.reference = 1;
s->pic.buffer_hints = FF_BUFFER_HINTS_VALID |
FF_BUFFER_HINTS_PRESERVE |
FF_BUFFER_HINTS_REUSABLE;
if ((ret = avctx->reget_buffer(avctx, &s->pic))) {
av_log(s->avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
return ret;
}
ftype = AV_RL32(avpkt->data);
switch (ftype) {
case 0:
ret = xan_decode_frame_type0(avctx, avpkt);
break;
case 1:
ret = xan_decode_frame_type1(avctx, avpkt);
break;
default:
av_log(avctx, AV_LOG_ERROR, "Unknown frame type %d\n", ftype);
return -1;
}
if (ret)
return ret;
*data_size = sizeof(AVFrame);
*(AVFrame*)data = s->pic;
return avpkt->size;
}
| 1threat
|
how to capitalize a first letter of each word in array in ES7 or ES8 : how to capitalize a first letter of each word in an array in ES7 or ES8
i tried this, but it didn't work.
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
days.map(day => day.charAt(0).toUpperCase() + day.substr(1));
console.log(day);
| 0debug
|
static int t15(InterplayACMContext *s, unsigned ind, unsigned col)
{
GetBitContext *gb = &s->gb;
unsigned i, b;
int n1, n2, n3;
for (i = 0; i < s->rows; i++) {
b = get_bits(gb, 5);
n1 = (mul_3x3[b] & 0x0F) - 1;
n2 = ((mul_3x3[b] >> 4) & 0x0F) - 1;
n3 = ((mul_3x3[b] >> 8) & 0x0F) - 1;
set_pos(s, i++, col, n1);
if (i >= s->rows)
break;
set_pos(s, i++, col, n2);
if (i >= s->rows)
break;
set_pos(s, i, col, n3);
return 0;
| 1threat
|
How to validate a JWT token : <p>I'm trying to use JWT tokens. I managed to generate a valid <code>JWTTokenString</code> and validated it on the <a href="https://jwt.io/" rel="noreferrer">JWT debugger</a> but I'm having an impossible time validating the token in .Net. Here's the code I have so far:</p>
<pre><code>class Program {
static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
static void Main(string[] args) {
var stringToken = GenerateToken();
ValidateToken(stringToken);
}
private static string GenerateToken() {
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var header = new JwtHeader(credentials);
var payload = new JwtPayload {
{ "some ", "hello "},
{ "scope", "world"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
return handler.WriteToken(secToken);
}
private static bool ValidateToken(string authToken) {
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = GetValidationParameters();
SecurityToken validatedToken;
IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
Thread.CurrentPrincipal = principal;
return true;
}
private static TokenValidationParameters GetValidationParameters() {
return new TokenValidationParameters() {
//NOT A CLUE WHAT TO PLACE HERE
};
}
}
</code></pre>
<p>All I want is a function that receives a token and returns true or false based on its validity. From research I've seen people use <code>IssuerSigningToken</code> to assign the validation key. But when I try to use it, it doesn't seem to exist. Could anyone give me a hand on validating the token?</p>
| 0debug
|
Split string on one use of a word and not the other : <p>fairly novice here, I'm looking for an effective way to use split() to split a string after a certain word.
I'm working on a voice controlled filter using the Csound API in python, and say my input command is "Set cutoff to 440", I'd like to split the string after the word "to", basically meaning that I can say the command however I like and it'll still find my frequency I'm looking for, I hope that makes sense.
So at the moment, my code for this is</p>
<pre><code>string = "set cutoff to 440"
split = string.split("to")
print(split)
</code></pre>
<p>and my output is</p>
<pre><code>['set', 'cu', 'ff', '440']
</code></pre>
<p>The problem is the 'to' in 'cutoff', I know I could fix this by just changing cutoff to frequency but it seems like giving in too easily. My suspicion is there's a way to do this with regular expressions, but I could easily be wrong, any advice would be really helpful, and I hope my post adhered to all the guidelines and stuff, am pretty new to Stack Overflow. </p>
| 0debug
|
C# string.split variances : <p>I have probably missed something very basic but this has me stumped.</p>
<p>When using String.Split() I get different results between </p>
<pre><code>.Split(' ')
</code></pre>
<p>and </p>
<pre><code>.Split(new char[' '])
</code></pre>
<p>Given this code:</p>
<pre><code>using (System.IO.StreamWriter sw = new StreamWriter(@"C:\consoleapp1.log", true))
{
string anystring = "pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2";
sw.WriteLine(".Split(' ')");
string[] anystrings1 = anystring.Split(' ');
for (int i = 0; i < anystrings1.Length; i++)
{
sw.WriteLine($@"{i,2}: {anystrings1[i]}");
}
sw.WriteLine(".Split(new char[' '])");
string[] anystrings2 = anystring.Split(new char[' ']);
for (int i = 0; i < anystrings2.Length; i++)
{
sw.WriteLine($@"{i,2}: {anystrings2[i]}");
}
}
</code></pre>
<p>Why do I get different results:</p>
<pre><code>.Split(' ')
0: pagelength=60
1: pagewidth=170
2: cpi=16
3: lpi=8
4: landscape=1
5: lm=2
.Split(new char[' '])
0: pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2
</code></pre>
| 0debug
|
void tcg_gen_callN(void *func, TCGTemp *ret, int nargs, TCGTemp **args)
{
TCGContext *s = tcg_ctx;
int i, real_args, nb_rets, pi;
unsigned sizemask, flags;
TCGHelperInfo *info;
TCGOp *op;
info = g_hash_table_lookup(helper_table, (gpointer)func);
flags = info->flags;
sizemask = info->sizemask;
#if defined(__sparc__) && !defined(__arch64__) \
&& !defined(CONFIG_TCG_INTERPRETER)
int orig_sizemask = sizemask;
int orig_nargs = nargs;
TCGv_i64 retl, reth;
TCGTemp *split_args[MAX_OPC_PARAM];
retl = NULL;
reth = NULL;
if (sizemask != 0) {
for (i = real_args = 0; i < nargs; ++i) {
int is_64bit = sizemask & (1 << (i+1)*2);
if (is_64bit) {
TCGv_i64 orig = temp_tcgv_i64(args[i]);
TCGv_i32 h = tcg_temp_new_i32();
TCGv_i32 l = tcg_temp_new_i32();
tcg_gen_extr_i64_i32(l, h, orig);
split_args[real_args++] = tcgv_i32_temp(h);
split_args[real_args++] = tcgv_i32_temp(l);
} else {
split_args[real_args++] = args[i];
}
}
nargs = real_args;
args = split_args;
sizemask = 0;
}
#elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64
for (i = 0; i < nargs; ++i) {
int is_64bit = sizemask & (1 << (i+1)*2);
int is_signed = sizemask & (2 << (i+1)*2);
if (!is_64bit) {
TCGv_i64 temp = tcg_temp_new_i64();
TCGv_i64 orig = temp_tcgv_i64(args[i]);
if (is_signed) {
tcg_gen_ext32s_i64(temp, orig);
} else {
tcg_gen_ext32u_i64(temp, orig);
}
args[i] = tcgv_i64_temp(temp);
}
}
#endif
i = s->gen_next_op_idx;
tcg_debug_assert(i < OPC_BUF_SIZE);
s->gen_op_buf[0].prev = i;
s->gen_next_op_idx = i + 1;
op = &s->gen_op_buf[i];
memset(op, 0, offsetof(TCGOp, args));
op->opc = INDEX_op_call;
op->prev = i - 1;
op->next = i + 1;
pi = 0;
if (ret != NULL) {
#if defined(__sparc__) && !defined(__arch64__) \
&& !defined(CONFIG_TCG_INTERPRETER)
if (orig_sizemask & 1) {
retl = tcg_temp_new_i64();
reth = tcg_temp_new_i64();
op->args[pi++] = tcgv_i64_arg(reth);
op->args[pi++] = tcgv_i64_arg(retl);
nb_rets = 2;
} else {
op->args[pi++] = temp_arg(ret);
nb_rets = 1;
}
#else
if (TCG_TARGET_REG_BITS < 64 && (sizemask & 1)) {
#ifdef HOST_WORDS_BIGENDIAN
op->args[pi++] = temp_arg(ret + 1);
op->args[pi++] = temp_arg(ret);
#else
op->args[pi++] = temp_arg(ret);
op->args[pi++] = temp_arg(ret + 1);
#endif
nb_rets = 2;
} else {
op->args[pi++] = temp_arg(ret);
nb_rets = 1;
}
#endif
} else {
nb_rets = 0;
}
op->callo = nb_rets;
real_args = 0;
for (i = 0; i < nargs; i++) {
int is_64bit = sizemask & (1 << (i+1)*2);
if (TCG_TARGET_REG_BITS < 64 && is_64bit) {
#ifdef TCG_TARGET_CALL_ALIGN_ARGS
if (real_args & 1) {
op->args[pi++] = TCG_CALL_DUMMY_ARG;
real_args++;
}
#endif
#if defined(HOST_WORDS_BIGENDIAN) != defined(TCG_TARGET_STACK_GROWSUP)
op->args[pi++] = temp_arg(args[i] + 1);
op->args[pi++] = temp_arg(args[i]);
#else
op->args[pi++] = temp_arg(args[i]);
op->args[pi++] = temp_arg(args[i] + 1);
#endif
real_args += 2;
continue;
}
op->args[pi++] = temp_arg(args[i]);
real_args++;
}
op->args[pi++] = (uintptr_t)func;
op->args[pi++] = flags;
op->calli = real_args;
tcg_debug_assert(op->calli == real_args);
tcg_debug_assert(pi <= ARRAY_SIZE(op->args));
#if defined(__sparc__) && !defined(__arch64__) \
&& !defined(CONFIG_TCG_INTERPRETER)
for (i = real_args = 0; i < orig_nargs; ++i) {
int is_64bit = orig_sizemask & (1 << (i+1)*2);
if (is_64bit) {
tcg_temp_free_internal(args[real_args++]);
tcg_temp_free_internal(args[real_args++]);
} else {
real_args++;
}
}
if (orig_sizemask & 1) {
tcg_gen_concat32_i64(temp_tcgv_i64(ret), retl, reth);
tcg_temp_free_i64(retl);
tcg_temp_free_i64(reth);
}
#elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64
for (i = 0; i < nargs; ++i) {
int is_64bit = sizemask & (1 << (i+1)*2);
if (!is_64bit) {
tcg_temp_free_internal(args[i]);
}
}
#endif
}
| 1threat
|
app enter background and then enter foreground will appear this bug (Splash Screen) : [about bug][1]
[1]: http://i.stack.imgur.com/AGeKu.gif
app enter background and then enter foreground will appear this bug (Splash Screen)
this bug only appear iPhone6 after
If you have ever had this experience, pls tell me thx
| 0debug
|
void restore_boot_order(void *opaque)
{
char *normal_boot_order = opaque;
static int first = 1;
if (first) {
first = 0;
return;
}
qemu_boot_set(normal_boot_order);
qemu_unregister_reset(restore_boot_order, normal_boot_order);
g_free(normal_boot_order);
}
| 1threat
|
static av_always_inline void filter_mb_dir(H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize, int mb_xy, int mb_type, int mvy_limit, int first_vertical_edge_done, int chroma, int chroma444, int dir) {
MpegEncContext * const s = &h->s;
int edge;
int chroma_qp_avg[2];
const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;
const int mbm_type = dir == 0 ? h->left_type[LTOP] : h->top_type;
static const uint8_t mask_edge_tab[2][8]={{0,3,3,3,1,1,1,1},
{0,3,1,1,3,3,3,3}};
const int mask_edge = mask_edge_tab[dir][(mb_type>>3)&7];
const int edges = mask_edge== 3 && !(h->cbp&15) ? 1 : 4;
const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));
if(mbm_type && !first_vertical_edge_done){
if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0)
&& IS_INTERLACED(mbm_type&~mb_type)
) {
unsigned int tmp_linesize = 2 * linesize;
unsigned int tmp_uvlinesize = 2 * uvlinesize;
int mbn_xy = mb_xy - 2 * s->mb_stride;
int j;
for(j=0; j<2; j++, mbn_xy += s->mb_stride){
DECLARE_ALIGNED(8, int16_t, bS)[4];
int qp;
if (IS_INTRA(mb_type | s->current_picture.f.mb_type[mbn_xy])) {
AV_WN64A(bS, 0x0003000300030003ULL);
} else {
if (!CABAC && IS_8x8DCT(s->current_picture.f.mb_type[mbn_xy])) {
bS[0]= 1+((h->cbp_table[mbn_xy] & 0x4000)||h->non_zero_count_cache[scan8[0]+0]);
bS[1]= 1+((h->cbp_table[mbn_xy] & 0x4000)||h->non_zero_count_cache[scan8[0]+1]);
bS[2]= 1+((h->cbp_table[mbn_xy] & 0x8000)||h->non_zero_count_cache[scan8[0]+2]);
bS[3]= 1+((h->cbp_table[mbn_xy] & 0x8000)||h->non_zero_count_cache[scan8[0]+3]);
}else{
const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy] + 3*4;
int i;
for( i = 0; i < 4; i++ ) {
bS[i] = 1 + !!(h->non_zero_count_cache[scan8[0]+i] | mbn_nnz[i]);
}
}
}
Do not use s->qscale as luma quantizer because it has not the same
value in IPCM macroblocks.
qp = (s->current_picture.f.qscale_table[mb_xy] + s->current_picture.f.qscale_table[mbn_xy] + 1) >> 1;
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);
{ int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
filter_mb_edgeh( &img_y[j*linesize], tmp_linesize, bS, qp, h );
chroma_qp_avg[0] = (h->chroma_qp[0] + get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mbn_xy]) + 1) >> 1;
chroma_qp_avg[1] = (h->chroma_qp[1] + get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mbn_xy]) + 1) >> 1;
if (chroma) {
if (chroma444) {
filter_mb_edgeh (&img_cb[j*uvlinesize], tmp_uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgeh (&img_cr[j*uvlinesize], tmp_uvlinesize, bS, chroma_qp_avg[1], h);
} else {
filter_mb_edgech(&img_cb[j*uvlinesize], tmp_uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgech(&img_cr[j*uvlinesize], tmp_uvlinesize, bS, chroma_qp_avg[1], h);
}
}
}
}else{
DECLARE_ALIGNED(8, int16_t, bS)[4];
int qp;
if( IS_INTRA(mb_type|mbm_type)) {
AV_WN64A(bS, 0x0003000300030003ULL);
if ( (!IS_INTERLACED(mb_type|mbm_type))
|| ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))
)
AV_WN64A(bS, 0x0004000400040004ULL);
} else {
int i;
int mv_done;
if( dir && FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbm_type)) {
AV_WN64A(bS, 0x0001000100010001ULL);
mv_done = 1;
}
else if( mask_par0 && ((mbm_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {
int b_idx= 8 + 4;
int bn_idx= b_idx - (dir ? 8:1);
bS[0] = bS[1] = bS[2] = bS[3] = check_mv(h, 8 + 4, bn_idx, mvy_limit);
mv_done = 1;
}
else
mv_done = 0;
for( i = 0; i < 4; i++ ) {
int x = dir == 0 ? 0 : i;
int y = dir == 0 ? i : 0;
int b_idx= 8 + 4 + x + 8*y;
int bn_idx= b_idx - (dir ? 8:1);
if( h->non_zero_count_cache[b_idx] |
h->non_zero_count_cache[bn_idx] ) {
bS[i] = 2;
}
else if(!mv_done)
{
bS[i] = check_mv(h, b_idx, bn_idx, mvy_limit);
}
}
}
Do not use s->qscale as luma quantizer because it has not the same
value in IPCM macroblocks.
if(bS[0]+bS[1]+bS[2]+bS[3]){
qp = (s->current_picture.f.qscale_table[mb_xy] + s->current_picture.f.qscale_table[mbm_xy] + 1) >> 1;
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp[0], s->current_picture.qscale_table[mbn_xy]);
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
{ int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
chroma_qp_avg[0] = (h->chroma_qp[0] + get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mbm_xy]) + 1) >> 1;
chroma_qp_avg[1] = (h->chroma_qp[1] + get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mbm_xy]) + 1) >> 1;
if( dir == 0 ) {
filter_mb_edgev( &img_y[0], linesize, bS, qp, h );
if (chroma) {
if (chroma444) {
filter_mb_edgev ( &img_cb[0], uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgev ( &img_cr[0], uvlinesize, bS, chroma_qp_avg[1], h);
} else {
filter_mb_edgecv( &img_cb[0], uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgecv( &img_cr[0], uvlinesize, bS, chroma_qp_avg[1], h);
}
}
} else {
filter_mb_edgeh( &img_y[0], linesize, bS, qp, h );
if (chroma) {
if (chroma444) {
filter_mb_edgeh ( &img_cb[0], uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgeh ( &img_cr[0], uvlinesize, bS, chroma_qp_avg[1], h);
} else {
filter_mb_edgech( &img_cb[0], uvlinesize, bS, chroma_qp_avg[0], h);
filter_mb_edgech( &img_cr[0], uvlinesize, bS, chroma_qp_avg[1], h);
}
}
}
}
}
}
for( edge = 1; edge < edges; edge++ ) {
DECLARE_ALIGNED(8, int16_t, bS)[4];
int qp;
if( IS_8x8DCT(mb_type & (edge<<24)) ) (edge&1) && IS_8x8DCT(mb_type)
continue;
if( IS_INTRA(mb_type)) {
AV_WN64A(bS, 0x0003000300030003ULL);
} else {
int i;
int mv_done;
if( edge & mask_edge ) {
AV_ZERO64(bS);
mv_done = 1;
}
else if( mask_par0 ) {
int b_idx= 8 + 4 + edge * (dir ? 8:1);
int bn_idx= b_idx - (dir ? 8:1);
bS[0] = bS[1] = bS[2] = bS[3] = check_mv(h, b_idx, bn_idx, mvy_limit);
mv_done = 1;
}
else
mv_done = 0;
for( i = 0; i < 4; i++ ) {
int x = dir == 0 ? edge : i;
int y = dir == 0 ? i : edge;
int b_idx= 8 + 4 + x + 8*y;
int bn_idx= b_idx - (dir ? 8:1);
if( h->non_zero_count_cache[b_idx] |
h->non_zero_count_cache[bn_idx] ) {
bS[i] = 2;
}
else if(!mv_done)
{
bS[i] = check_mv(h, b_idx, bn_idx, mvy_limit);
}
}
if(bS[0]+bS[1]+bS[2]+bS[3] == 0)
continue;
}
Do not use s->qscale as luma quantizer because it has not the same
value in IPCM macroblocks.
qp = s->current_picture.f.qscale_table[mb_xy];
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp[0], s->current_picture.qscale_table[mbn_xy]);
tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);
{ int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }
if( dir == 0 ) {
filter_mb_edgev( &img_y[4*edge << h->pixel_shift], linesize, bS, qp, h );
if (chroma) {
if (chroma444) {
filter_mb_edgev ( &img_cb[4*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[0], h);
filter_mb_edgev ( &img_cr[4*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[1], h);
} else if( (edge&1) == 0 ) {
filter_mb_edgecv( &img_cb[2*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[0], h);
filter_mb_edgecv( &img_cr[2*edge << h->pixel_shift], uvlinesize, bS, h->chroma_qp[1], h);
}
}
} else {
filter_mb_edgeh( &img_y[4*edge*linesize], linesize, bS, qp, h );
if (chroma) {
if (chroma444) {
filter_mb_edgeh ( &img_cb[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[0], h);
filter_mb_edgeh ( &img_cr[4*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[1], h);
} else if( (edge&1) == 0 ) {
filter_mb_edgech( &img_cb[2*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[0], h);
filter_mb_edgech( &img_cr[2*edge*uvlinesize], uvlinesize, bS, h->chroma_qp[1], h);
}
}
}
}
}
| 1threat
|
Find the top 10 centre most values from each clusters done by k-means using python : <p>I have a data frame and I have clustered it into 3 clusters using k-means clustering. </p>
<p>Now I want to find the top 10 centre most values from each clusters. </p>
<p>How to do it using python ? </p>
| 0debug
|
static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
size_t size)
{
int64_t len;
if (size > INT_MAX) {
return -EIO;
}
if (!blk_is_available(blk)) {
return -ENOMEDIUM;
}
len = blk_getlength(blk);
if (len < 0) {
return len;
}
if (offset < 0) {
return -EIO;
}
if (offset > len || len - offset < size) {
return -EIO;
}
return 0;
}
| 1threat
|
Split the character vector into two parts : <p>Consider the following character vector of the length 1:</p>
<pre><code>l <- "http://www.idealo.de/preisvergleich/OffersOfProduct/4983410_-iphone-se-64gb-spacegrau-apple.html"
</code></pre>
<p>I desire to split it into two parts, so that the first part should be:</p>
<pre><code>p1 <- "http://www.idealo.de/preisvergleich/OffersOfProduct/4983410"
</code></pre>
<p>and the second one:</p>
<pre><code>p2 <- "_-iphone-se-64gb-spacegrau-apple.html"
</code></pre>
<p>Surely, one must use regexp to solve the problem. Please could you give me some insight where I can learn manipulation with regular expressions easily. For any help I will be sincerely thankful.</p>
| 0debug
|
Why will this array not stop looping in c : <p>I am trying to display a <a href="http://pages.mtu.edu/~shene/NSF-4/Tutorial/VIG/Vig-Base.html" rel="nofollow noreferrer">Vigenere Square</a> but the for loop that creates it will not stop looping past the counter. You can find the loop under choice 1. Also if someone knows how to make the decrypt function to work.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char encrypt(char, char);
char decrypt(char, char);
int main()
{
int choice;
printf("What would you like to do?\n\n");
printf("1. Show board\n");
printf("2. Encrypt\n");
printf("3. Decrypt\n");
printf("4. Exit\n");
scanf("%i", &choice);
while(choice != 4){
char key[9];
char input[51];
char decrypt[51];
if (choice == 3 || choice == 2){
printf("Give me a 9 character or less key in caps.\n");
scanf("%s", &key);
printf("Give me a 51 character or less string in caps.\n");
scanf("%s", &input);
}
if (choice==1){
int i, j;
for(i=0;i<=25;i++){
for(j=0;j<=25;j++){
printf("%c ", encrypt((char) i, (char) j));
}
printf("\n");
}
} else if (choice == 2){
int i;
char text_crypt[51];
for(i = 0; i < strlen(input); i++){
text_crypt[i] = encrypt(input[i], key[i % strlen(key)]);
}
printf("cyphertext is: %s\n", text_crypt);
} else if (choice == 3){
int i;
char text_crypt[51];
for(i = 0; i < strlen(input); i++){
text_crypt[i] = encrypt(input[i], key[i % strlen(key)]);
}
printf("cyphertext is: %s\n", text_crypt);
}
}
return 0;
}
char encrypt(char x, char y){
return 65+((x+y)%26);
}
char decrypt(char x, char y){
return 90-((x+y)%26);
}
</code></pre>
<p>I am trying to display a Vigenere Square but the for loop that creates it will not stop looping past the counter. You can find the loop under choice 1. Also if someone knows how to make the decrypt function to work.</p>
| 0debug
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.