problem
stringlengths 26
131k
| labels
class label 2
classes |
|---|---|
What are the programming languages for stalking facebook friends : <p>I would like your guidance. Could you suggest me a programming languages capable of monitoring my Facebook friends activity?
By activity I mean:</p>
<ul>
<li>Know when they get online</li>
<li>Know when they post something</li>
<li>Know which are my friends that contribute more in likes/comments in my profile in the last <em>X</em> hour </li>
</ul>
| 0debug
|
How do I cout items right below the category? : [image][1]
[1]: http://i.stack.imgur.com/zvKLa.png
Yeah so I guess the question is self evident from the image,I want the output text to be right below its category(eg. ID, name etc.)
Here is the code snippet:
FILE *fp;
fp = fopen("Records.txt","r");
cout<<"Category ID Name Author Quantity Price Rack\n\n";
while(fread(&b,sizeof(b),1,fp)==1){
cout<<b.category<<" "<<b.id<<" "<<b.name<<" "<<b.author<<" "<<b.quantity<<" "<<b.price<<" "<<b.rackno;
cout<<endl<<endl;
}
fclose(fp);
Where "b" is object of class BOOK
Thank YOU!
| 0debug
|
diference c++ passing argument methods : What is the difference in passing base class constructor in your derived class in these two different ways 1) Dog::Dog(string input_name , int input_age ): Pet(input_name, input_age) { } 2) Dog::Dog(string input_name , int input_age ) {Pet(input_name, input_age) }
| 0debug
|
How to DRY when using Swagger UI and the ApiResponses annotations with Java Spring endpoints? : <p>I like <code>Swagger</code> because it makes your apis very user friendly. I use <code>Swagger</code> annotations like</p>
<ul>
<li>@ApiParam </li>
<li>@ApiResponse | @ApiResponses </li>
<li>@ApiOperation </li>
<li>Others </li>
</ul>
<p>On endpoints, query params, request params, request body and so on. </p>
<p>I like to keep my <code>POJO</code> classes clean and in general I try my best to follow <code>DRY</code> rule however, when it comes to swagger I noticed that I keep <strong>repeating</strong> myself over and over as shown below</p>
<pre><code>@ApiOperation(value = "Retrieve object by id")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 500, message = "ISE")
})
public Response retrieveById(@ApiParam(value = "Some id") @PathParam("sid") int id) {
}
@ApiOperation(value = "Create object")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Created"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 500, message = "ISE")
})
public Response create(@ApiParam(value = "Request body") RequestBody body) {
}
</code></pre>
<p>How to avoid repeating yourself with <code>Swagger annotations</code>? </p>
| 0debug
|
int add_exec(struct ex_list **ex_ptr, int do_pty, char *exec,
struct in_addr addr, int port)
{
struct ex_list *tmp_ptr;
for (tmp_ptr = *ex_ptr; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {
if (port == tmp_ptr->ex_fport &&
addr.s_addr == tmp_ptr->ex_addr.s_addr)
return -1;
}
tmp_ptr = *ex_ptr;
*ex_ptr = (struct ex_list *)malloc(sizeof(struct ex_list));
(*ex_ptr)->ex_fport = port;
(*ex_ptr)->ex_addr = addr;
(*ex_ptr)->ex_pty = do_pty;
(*ex_ptr)->ex_exec = (do_pty == 3) ? exec : strdup(exec);
(*ex_ptr)->ex_next = tmp_ptr;
return 0;
}
| 1threat
|
android studio : error in Type in number in edittext then do math on it and show result : hi the title says it all
here is the code
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
ImageButton imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
ImageButton imageButton3= (ImageButton) findViewById(R.id.imageButton3);
ImageButton imageButton4 = (ImageButton) findViewById(R.id.imageButton4);
ImageButton imageButton5 = (ImageButton) findViewById(R.id.imageButton5);
ImageButton imageButton6 = (ImageButton) findViewById(R.id.imageButton6);
ImageButton imageButton7 = (ImageButton) findViewById(R.id.imageButton7);
ImageButton imageButton8 = (ImageButton) findViewById(R.id.imageButton8);
ImageButton imageButton9 = (ImageButton) findViewById(R.id.imageButton9);
final EditText editText = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
final TextView textView50 = (TextView)findViewById(R.id.textView50);
//here where the android monitor says it error
final int dayNumber = Integer.parseInt(editText.getText().toString());
editText2.getText();
editText3.getText();
imageButton3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = dayNumber * 4;
textView50.setText(String.valueOf(a));
}
});
and here is the android monitor result
07-31 19:45:54.353 19858-19858/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: ahmednageeb.com.yourageinotherplanets, PID: 19858
java.lang.RuntimeException: Unable to start activity ComponentInfo{ahmednageeb.com.package/ahmednageeb.com.package.Main2Activity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at ahmednageeb.com.package.Main2Activity.onCreate(Main2Activity.java:40)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-31 19:45:56.587 19858-19858/ahmednageeb.com.package I/Process: Sending signal. PID: 19858 SIG: 9
| 0debug
|
Multiple jenkinsfile in one repository : <p>We have a project in a Github repository with multiple Jenkinsfiles:</p>
<pre><code>my-project
app
Jenkinsfile
lib1
Jenkinsfile
lib2
Jenkinsfile
</code></pre>
<p>We have created 3 Jenkins pipelines each referring to a Jenkinsfile.
<a href="https://i.stack.imgur.com/wfNLH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wfNLH.png" alt="enter image description here"></a></p>
<p>Question: How to avoid triggering "app" and "lib1" pipelines when there is a new commit in "lib2"? We don't want to run N jobs every time a commit happens.</p>
<p>I've seen that the issue is addressed in <a href="https://issues.jenkins-ci.org/browse/JENKINS-43749" rel="noreferrer">https://issues.jenkins-ci.org/browse/JENKINS-43749</a>, but I haven't found a solution there.</p>
| 0debug
|
static int msvideo1_decode_init(AVCodecContext *avctx)
{
Msvideo1Context *s = avctx->priv_data;
s->avctx = avctx;
if (s->avctx->palctrl) {
s->mode_8bit = 1;
avctx->pix_fmt = PIX_FMT_PAL8;
} else {
s->mode_8bit = 0;
avctx->pix_fmt = PIX_FMT_RGB555;
}
dsputil_init(&s->dsp, avctx);
s->frame.data[0] = NULL;
return 0;
}
| 1threat
|
Voximal : Unable to call asteri : I try to get the softphone connected to our instance for playing with our app,
but I failed to get the psw
https://wiki.voximal.com/doku.php?id=installation_guide:softphone:start
In the web Interface is no psw mentioned
And for the astreisk console, I got no Access to cli , error orrcured?
May you can help me on short, since I just try to get it work
Thanks in advance
Andreas
| 0debug
|
My C code gives me result that is not correct(array operation) : It should be simple,two arrays,one with 5 other with 6 elements.
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0;
int k=0;
int v[5] = {2,3,4,5,6};
int g[6];
for( i = 1; i <= 6; i++ ){
k= i + 1;
if ( 1 == i && 2 == i)
{
g[k]=v[i];
}
else
{
g[k]=(v[i]+10);
}
printf("%d\n",g[k]);
}
return 0;
}
I got this
13
14
15
16
32776
10
I really wanted
2 3 13 14 15 16
Where is my mistake?Should I create function or what?
| 0debug
|
Extracting Value from JSON variable : <p>I'm trying to extract a value called "balanceStr" from a web scraper I'm making, but I'm not having much luck!</p>
<p>Here's where I got so far:</p>
<pre><code>import requests
import json
url = "https://www.hpbscan.org/HpbScan/addrs/getAddressDetailInfo"
headers = {'Content-Type': 'application/json;charset=utf-8'}
body = '["0x7EC332476fCA4Bcd20176eE06F16960b5D49333e"]'
data = requests.post(url, data=body, headers=headers)
json_data = (json.loads(data.text))
#print(json_data)
print(json_data['balanceStr'])
</code></pre>
<p>If I just print(json_data) this is the output, but I'm just trying to get the value of balanceStr (36885.403...) in a variable so that I can use it like print(currentbalance)</p>
<pre><code>[
"000000",
"\u6210\u529f",
{
"addrs": {
"accountType": null,
"address": "0x7ec332476fca4bcd20176ee06f16960b5d49333e",
"assetRankingOrder": "150",
"balance": 36885403823844342504238,
"balanceStr": "36885.40382384",
"createTimestamp": 1569209857000,
"fromCount": 22,
"lastestBlock": 3951440,
"map": {},
"number": 229,
"percentRate": "0.0369%",
"startBlock": 51601,
"toCount": 15
},
"hpbInstantPrice": {
"changePercent": "-6.65%",
"cnyPrice": "1.9890",
"id": 1,
"map": {},
"updateTime": 1569210840000,
"usdPrice": "0.2791"
},
"nonce": 22
}
]
</code></pre>
<p>When I print(json_data['balanceStr']) this is the error I'm getting:</p>
<pre><code> print(json_data['addrs'])
TypeError: list indices must be integers or slices, not str
</code></pre>
<p>Any help would be much appreciated!</p>
| 0debug
|
static int fill_note_info(struct elf_note_info *info,
long signr, const CPUState *env)
{
#define NUMNOTES 3
CPUState *cpu = NULL;
TaskState *ts = (TaskState *)env->opaque;
int i;
(void) memset(info, 0, sizeof (*info));
TAILQ_INIT(&info->thread_list);
info->notes = qemu_mallocz(NUMNOTES * sizeof (struct memelfnote));
if (info->notes == NULL)
return (-ENOMEM);
info->prstatus = qemu_mallocz(sizeof (*info->prstatus));
if (info->prstatus == NULL)
return (-ENOMEM);
info->psinfo = qemu_mallocz(sizeof (*info->psinfo));
if (info->prstatus == NULL)
return (-ENOMEM);
fill_prstatus(info->prstatus, ts, signr);
elf_core_copy_regs(&info->prstatus->pr_reg, env);
fill_note(&info->notes[0], "CORE", NT_PRSTATUS,
sizeof (*info->prstatus), info->prstatus);
fill_psinfo(info->psinfo, ts);
fill_note(&info->notes[1], "CORE", NT_PRPSINFO,
sizeof (*info->psinfo), info->psinfo);
fill_auxv_note(&info->notes[2], ts);
info->numnote = 3;
info->notes_size = 0;
for (i = 0; i < info->numnote; i++)
info->notes_size += note_size(&info->notes[i]);
cpu_list_lock();
for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
if (cpu == thread_env)
continue;
fill_thread_info(info, cpu);
}
cpu_list_unlock();
return (0);
}
| 1threat
|
qemu_irq sh7750_irl(SH7750State *s)
{
sh_intc_toggle_source(sh_intc_source(&s->intc, IRL), 1, 0);
return qemu_allocate_irqs(sh_intc_set_irl, sh_intc_source(&s->intc, IRL),
1)[0];
}
| 1threat
|
int64_t qemu_strtosz_MiB(const char *nptr, char **end)
{
return do_strtosz(nptr, end, 'M', 1024);
}
| 1threat
|
i wrote a code for binary search and kept getting this error "TypeError: unsupported operand type(s) for //: 'list' and 'int'" : def binary_search(arr,val):
if len(arr)==0 or len(arr)==1 and arr[0]!=val:
return false
mid=arr[len(arr)//2]
if val==mid:
return true
if val<mid:
return binary_search(len(arr//2,val))
if val>mid:
return binary_search(len(arr//2+1,val))
arr=[1,2,3,4,5,6]
print(binary_search(arr,3))
| 0debug
|
How the gitlab-ci cache is working on docker runner? what is /cache directory? what is cache_dir? : <ol>
<li><p>How the gitlab-ci cache is working on docker runner? </p></li>
<li><p>What is /cache directory? </p></li>
<li><p>What is cache_dir?</p></li>
<li><p>Where and how files matching the <a href="https://docs.gitlab.com/ee/ci/yaml/#cachepaths" rel="noreferrer">"paths" in "cache" gitlab-ci.yml</a> are stored?</p></li>
</ol>
| 0debug
|
Read an excel file on asp.net core 1.0 : <p>Hello I`m trying to upload and read an excel file on my asp.net project but all the documentation I find is for ASP MVC 5.
My goal is to read the excel sheet and pass the values to an list of objects.</p>
<p>This is my controller, it works for upload the file to my wwwroot/uploads</p>
<pre><code>public class HomeController : Controller
{
private IHostingEnvironment _environment;
public HomeController(IHostingEnvironment environment)
{
_environment = environment;
}
public IActionResult index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return View();
}
</code></pre>
| 0debug
|
static int mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
{
int category_index[128];
int quant_index_table[102];
int category[128];
int ret;
memset(&category, 0, sizeof(category));
memset(&category_index, 0, sizeof(category_index));
if ((ret = decode_envelope(q, p, quant_index_table)) < 0)
return ret;
q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
categorize(q, p, quant_index_table, category, category_index);
expand_category(q, category, category_index);
decode_vectors(q, p, category, quant_index_table, mlt_buffer);
return 0;
}
| 1threat
|
Getting the ClaimsPrincipal in a logic layer in an aspnet core 1 application : <p>I'm writing an aspnet core 1 application.
Using a bearer token authentication I have the User property inside the controller with the correct identity. However I cant seem to find a way to grab with identity as I did before using the <code>ClaimPrincipal.Current</code> static.
What is the current best practice to get this data inside the BL layers with out passing the ClaimPrincipal object around?</p>
| 0debug
|
RestFuse vs Rest Assured vs MockMVC Rest Service Unit Test Framework : <p>I've been trying to find a simple all purpose unit test framework for Spring MVC based Rest Services I've written.</p>
<p>I've been searching online and narrowed it down to:</p>
<ul>
<li>RestFuse (<a href="http://developer.eclipsesource.com/restfuse/" rel="noreferrer">http://developer.eclipsesource.com/restfuse/</a>)</li>
<li>Rest Assured (<a href="https://github.com/jayway/rest-assured" rel="noreferrer">https://github.com/jayway/rest-assured</a>)</li>
<li>MockMVC (<a href="http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/" rel="noreferrer">http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/</a>)</li>
</ul>
<p>I like RestFuse because it's mostly annotation based, but rest assured seems to have a easier way of passing parameters and checking responses. And finally being a Spring MVC Rest Service project, I'm wondering if I should just stick with the already established way of testing Rest Services in Spring with MockMVC.</p>
<p>Interested to get any feedback, as well as performance, past experiences and if there's anything else I should take into consideration.</p>
| 0debug
|
Problem with SDL_FINGERDOWN : I don't why SDL_FINGERDOWN records
even simple touch event.It should register on Sliding finger down as name says right?I use android N for testing
Here is my code
#include "SDL.h"
#include <SDL2/SDL.h>
#include<iostream>
using namespace std;
int main(int argc,char *argv[]){
SDL_Init(SDL_INIT_EVERYTHING);
int r,g,b;
r=g=b=0;
SDL_Window *window; window=SDL_CreateWindow("S",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,720,1320,SDL_WINDOW_RESIZABLE);
SDL_Surface *screen=SDL_GetWindowSurface(window);
Uint32 white=SDL_MapRGB(screen->format,255,255,255);
SDL_FillRect(screen,NULL,white);
SDL_UpdateWindowSurface(window);
SDL_Event event;
bool running=true;
while(running){
while(SDL_PollEvent(&event)){
if(event.type==SDL_FINGERDOWN){
running=false;
break;
}
//end if
}//end inner while
}
SDL_DestroyWindow(window);
SDL_Quit();
}
| 0debug
|
Deal with relative and absolute path : My script should open file properly whether it gets relative or absolute path as an argument.
There is something shorter and better that this my try?
def main():
if os.path.isabs(sys.argv[1]):
filename = sys.argv[1]
else:
dir = os.path.dirname(__file__)
filename = os.path.join(dir, sys.argv[1])
assert os.path.exists(filename)
print(filename) # or whatever I want to do with the path..
| 0debug
|
static void compute_pts_dts(AVStream *st, int64_t *ppts, int64_t *pdts,
int64_t timestamp)
{
int frame_delay;
int64_t pts, dts;
if (st->codec.codec_type == CODEC_TYPE_VIDEO &&
st->codec.max_b_frames != 0) {
frame_delay = (st->codec.frame_rate_base * 90000LL) /
st->codec.frame_rate;
if (timestamp == 0) {
pts = timestamp;
dts = timestamp - frame_delay;
} else {
timestamp -= frame_delay;
if (st->codec.coded_frame->pict_type == FF_B_TYPE) {
pts = timestamp;
dts = timestamp;
} else {
dts = timestamp;
pts = timestamp + (st->codec.max_b_frames + 1) * frame_delay;
}
}
#if 1
av_log(&st->codec, AV_LOG_DEBUG, "pts=%0.3f dts=%0.3f pict_type=%c\n",
pts / 90000.0, dts / 90000.0,
av_get_pict_type_char(st->codec.coded_frame->pict_type));
#endif
} else {
pts = timestamp;
dts = timestamp;
}
*ppts = pts & ((1LL << 33) - 1);
*pdts = dts & ((1LL << 33) - 1);
}
| 1threat
|
resources when opening a website : When we open a website, the browser will retrieve other resources, not just the site link itself. I'd like to know what are all those resources and the links that browser connect during a site's open. Is there a tool to determine this thing?
Thanks everyone.
| 0debug
|
TSLint in Visual Studio 2015/2017? : <p>My organization uses <a href="https://github.com/palantir/tslint/" rel="noreferrer">TSLint</a> pretty heavily for quality-checking our Typescript code, and it provides a valuable service to us! However, we use Visual Studio 2015 & 2017 as our main IDE and the only way to get the linting results it to run a gulp/grunt task which prints the output to the Task Runner Explorer console. It works, but it's slow and not the best development experience.</p>
<p>In smaller projects on my own I've used VSCode, which has <a href="https://marketplace.visualstudio.com/items?itemName=eg2.tslint" rel="noreferrer">a fantastic TSLint plugin</a> that highlights linting violations as you make them, and provides access to the auto-fixers that some TSLint rules have. Like this: </p>
<p><a href="https://i.stack.imgur.com/WdN0C.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/WdN0C.gif" alt="VSCode TSLint example"></a></p>
<p><strong>Is it possible to get this same functionality in Visual Studio 2015/2017?</strong> The immediate feedback is a life saver when writing TypeScript code. </p>
| 0debug
|
read, compare, and save 2 files with shell script (little more then what it sounds like) : <p>So I didn't quite get the answer I was looking for before, so here we go again;</p>
<p>I'm creating a script that searches IPs from a.csv log file against pre-defined blacked IP lists. </p>
<p>It first imports the log file, then parses IPs from it, then searches the parsed IPs against pre-defined blacked IP list, finally it needs to ask user (if any result found) to save the results to the original log file that was imported. </p>
<p>File 1 is a example of IP-output.csv in the code.</p>
<p>File 2 is a example of $filename in the code (original imported .csv).</p>
<p>File 1:</p>
<pre><code>107.147.166.60 ,SUSPICIOUS IP
107.147.167.26 ,SUSPICIOUS IP
108.48.185.186 ,SUSPICIOUS IP
108.51.114.130 ,SUSPICIOUS IP
142.255.102.68 ,SUSPICIOUS IP
</code></pre>
<p>File 2:</p>
<pre><code>outlook.office365.com ,174.203.0.118 ,UserLoginFailed
outlook.office365.com ,107.147.166.60 ,UserLoginFailed
outlook.office365.com ,107.147.167.26 ,UserLoginFailed
outlook.office365.com ,174.205.17.24 ,UserLoginFailed
outlook.office365.com ,108.48.185.186 ,UserLoginFailed
outlook.office365.com ,174.226.15.21 ,UserLoginFailed
outlook.office365.com ,108.51.114.130 ,UserLoginFailed
outlook.office365.com ,67.180.23.93 ,UserLoginFailed
outlook.office365.com ,142.255.102.68 ,UserLoginFailed
outlook.office365.com ,164.106.75.235 ,UserLoginFailed
</code></pre>
<p>I wanna change File 2 to this:</p>
<pre><code>outlook.office365.com ,174.203.0.118 ,UserLoginFailed
outlook.office365.com ,107.147.166.60 ,UserLoginFailed ,SUSPICIOUS IP
outlook.office365.com ,107.147.167.26 ,UserLoginFailed ,SUSPICIOUS IP
outlook.office365.com ,174.205.17.24 ,UserLoginFailed
outlook.office365.com ,108.48.185.186 ,UserLoginFailed ,SUSPICIOUS IP
outlook.office365.com ,174.226.15.21 ,UserLoginFailed
outlook.office365.com ,108.51.114.130 ,UserLoginFailed ,SUSPICIOUS IP
outlook.office365.com ,67.180.23.93 ,UserLoginFailed
outlook.office365.com ,142.255.102.68 ,UserLoginFailed ,SUSPICIOUS IP
outlook.office365.com ,164.106.75.235 ,UserLoginFailed
</code></pre>
<p>This is the script I created:</p>
<pre><code>#!/bin/bash
#
# IP Blacklist Checker
#Import .csv (File within working directory)
echo "Please import a .csv log file to parse/search the IP(s) and UserAgents: "
read filename
#Parsing IPs from .csv log file
echo "Parsing IP(s) from imported log file..."
grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' $filename | sort | uniq > IP-list.txt
echo 'Done'
awk 'END {print NR,"IP(s) Found in imported log file"}' IP-list.txt
echo 'IPs found in imported log file:'
cat IP-list.txt
#searches parsed ip's against blacked ip lists
echo 'Searching parsed IP(s) from pre-defined Blacked IP List Databases...'
fgrep -w -f "IP-list.txt" "IPlist.txt" > IP-output.txt
awk 'END {print NR,"IP(s) Found Blacked IP List Databases"}' IP-output.txt
echo 'Suspicious IPs found in Blacked IP List Databases:'
cat IP-output.txt
while true; do
read -p "Do you want to add results to log file?" yn
case $yn in
[Yy]* ) grep -Ff IP-output.txt $filename | sed 's/$/ ,SUSPICIOUS IP/' > IP-output.csv && awk 'FNR==NR {m[$1]=$0; next} {for (i in m) {match($0,i); val=substr($0, RSTART, RLENGTH); if (val) {sub(val, m[i]); print; next}};} 1' IP-output.csv $filename > $filename; break;;
[Nn]* ) break;;
* ) echo "Please answer yes or no.";;
esac
done
echo "Finished searching parsed IP(s) from pre-defined Blacked IP List Databases."
rm IP-list.txt IP-output.csv IP-output.txt
</code></pre>
<p>The log file I'm importing is really long with 15-20 columns, and the IPlist.txt (blacked IPs) has over 15000 IPs in it. After saving the results to the same log file, .csv file gets empty, and if I save it under a different name, all the columns go out of order, and the ", SUSPICIOUS IP" column appears next to the IP column, I need it instead to be at the last column (end of the line).</p>
<p>I also don't know how to prompt to save for a file only if anything was found, if not only prompt nothing found!</p>
<p>The results i'm getting:</p>
<pre><code> outlook.office365.com ,174.203.0.118 ,UserLoginFailed
outlook.office365.com ,107.147.166.60 ,SUSPICIOUS IP ,UserLoginFailed
outlook.office365.com ,107.147.167.26 ,SUSPICIOUS IP ,UserLoginFailed
outlook.office365.com ,174.205.17.24 ,UserLoginFailed
outlook.office365.com ,108.48.185.186 ,SUSPICIOUS IP ,UserLoginFailed
outlook.office365.com ,174.226.15.21 ,UserLoginFailed
outlook.office365.com ,108.51.114.130 ,SUSPICIOUS IP ,UserLoginFailed
outlook.office365.com ,67.180.23.93 ,UserLoginFailed
outlook.office365.com ,142.255.102.68 ,SUSPICIOUS IP ,UserLoginFailed
outlook.office365.com ,164.106.75.235 ,UserLoginFailed
</code></pre>
| 0debug
|
static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec,
int *sample_rate, int *output_sample_rate)
{
MPEG4AudioConfig mp4ac;
if (avpriv_mpeg4audio_get_config(&mp4ac, codec->extradata,
codec->extradata_size * 8, 1) < 0) {
av_log(s, AV_LOG_WARNING,
"Error parsing AAC extradata, unable to determine samplerate.\n");
return;
}
*sample_rate = mp4ac.sample_rate;
*output_sample_rate = mp4ac.ext_sample_rate;
}
| 1threat
|
static int pps_range_extensions(GetBitContext *gb, AVCodecContext *avctx,
HEVCPPS *pps, HEVCSPS *sps) {
int i;
if (pps->transform_skip_enabled_flag) {
pps->log2_max_transform_skip_block_size = get_ue_golomb_long(gb) + 2;
}
pps->cross_component_prediction_enabled_flag = get_bits1(gb);
pps->chroma_qp_offset_list_enabled_flag = get_bits1(gb);
if (pps->chroma_qp_offset_list_enabled_flag) {
pps->diff_cu_chroma_qp_offset_depth = get_ue_golomb_long(gb);
pps->chroma_qp_offset_list_len_minus1 = get_ue_golomb_long(gb);
if (pps->chroma_qp_offset_list_len_minus1 && pps->chroma_qp_offset_list_len_minus1 >= 5) {
av_log(avctx, AV_LOG_ERROR,
"chroma_qp_offset_list_len_minus1 shall be in the range [0, 5].\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i <= pps->chroma_qp_offset_list_len_minus1; i++) {
pps->cb_qp_offset_list[i] = get_se_golomb_long(gb);
if (pps->cb_qp_offset_list[i]) {
av_log(avctx, AV_LOG_WARNING,
"cb_qp_offset_list not tested yet.\n");
}
pps->cr_qp_offset_list[i] = get_se_golomb_long(gb);
if (pps->cr_qp_offset_list[i]) {
av_log(avctx, AV_LOG_WARNING,
"cb_qp_offset_list not tested yet.\n");
}
}
}
pps->log2_sao_offset_scale_luma = get_ue_golomb_long(gb);
pps->log2_sao_offset_scale_chroma = get_ue_golomb_long(gb);
return(0);
}
| 1threat
|
Updating sqlalchemy with boolean value from form : <p>I'm trying to update a row in a database table with a value from a wtforms BooleanField. When creating the row, it's inserted into the database with no problem, but when updating I get the error below.</p>
<p>When reading around this issue, it seems it's something to do with the initalising of the type of Boolean value the database should accept. In my sqlite db, the column contains 1/0, but I'm not sure how to fix it. It seems strange that the initial insert is fine, but updates are not. wtforms documentation mentions that the checked.data in the HTML returns a True or False value.</p>
<pre><code>class Question(PaginatedAPIMixin, db.Model):
__tablename__ = 'question'
...
answer_space = db.Column(db.Boolean, server_default="False")
...
class QuestionForm(FlaskForm):
...
answer_space = BooleanField('Generate space for question answer automatically?',default="checked")
...
# inside add question route
if form.validate_on_submit():
question = Question(body=form.body.data,
answer_space=form.answer_space.data,
author=current_user,
exam_level = form.exam_level.data,
exam_board=form.exam_board.data,
exam_year=form.exam_year.data,
exam_session=form.exam_session.data,
marks=form.marks.data,
answer=form.answer.data,
)
...
db.session.add(question)
db.session.commit()
#inside update question route
if form.validate_on_submit():
question.body = form.body.data
question.answer_space = form.answer_space.data,
question.exam_board=form.exam_board.data
question.exam_level = form.exam_level.data
question.exam_year=form.exam_year.data
question.exam_session=form.exam_session.data
question.marks=form.marks.data
question.answer=form.answer.data
...
db.session.commit()
flash('Your changes have been saved.', 'success')
return redirect(url_for('main.view_questions'))
</code></pre>
<p>sqlalchemy.exc.StatementError: (builtins.TypeError) Not a boolean value: False
[SQL: UPDATE question SET exam_session=?, answer_space=? WHERE question.id = ?]
[parameters: [{'answer_space': (False,), 'exam_session': '1', 'question_id': 12}]]</p>
| 0debug
|
Factoring try catch : <p>I have a Java EE application with dozens of web services using the same pattern:</p>
<pre><code>public Response myWebService1() {
try {
// do something different depending on the web service called
} catch (MyCustomException e1) {
return Response.status(409).build();
} catch (UnauthorizedException e2) {
return Response.status(401).build();
} catch (Exception e3) {
return Response.status(500).build();
}
}
</code></pre>
<p>Is that possible to factorize this piece of code?</p>
| 0debug
|
How to get week name from selected date month and year in android? : I tried below code but it gives two days ago week name
DatePicker picker;
int date = picker.DayOfMonth;
int month = (picker.Month + 1);//month is 0 based
int year = picker.Year;
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE");
Date dt = new Date(year, month, date);
| 0debug
|
Angular 2: How to prevent a form from submitting on keypress enter? : <p>I have a form with one field that acts as autocomplete. If the user enters a word and presses enter, the content of the field should be added to a list below the field.</p>
<p>The problem: When the user hits enter, naturally the whole form is being submitted.</p>
<p>I already <code>return false</code> on the function that handles the keypress. But the form seems to be submitted even before this function is called.</p>
<p>How do I prevent this from happening?</p>
<p>The basic form:</p>
<pre><code><div id="profileForm">
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" method="post" *ngIf="!showSuccessMessage">
<div class="row">
<div class="form-group col-xs-12 col-sm-6">
<label for="first_name">My Skills</label>
<div class="autocomplete">
<input formControlName="skill_string" [(ngModel)]="skillString" name="skill_string"
type="text" class="form-control" id="skill_string" placeholder="Comma separated" (keyup.enter)="skillsHandleEnter(skillString)">
<ul class="autocomplete-list" *ngIf="skillHints.length > 0">
<li class="list-item" *ngFor="let skill of skillHints" (click)="addSkillFromAutocomplete(skill)">{{skill}}</li>
</ul>
</div>
<div id="skill-cloud" class="tag-cloud">
<span class="skill-tag tag label label-success" *ngFor="let skill of selectedSkills" (click)="removeSkill(skill)">{{skill}} x</span>
</div>
</div>
</div>
<div class="row">
<hr>
<div class="form-group submit-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary pull-right" [disabled]="!profileForm.valid">Save</button>
</div>
</div>
</div>
</form>
</div>
</code></pre>
<p>The basic component (I stripped a lot of the logic for posting it here):</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import 'rxjs/add/operator/debounceTime';
import * as _ from 'lodash';
import { MemberService } from '../shared/index';
@Component({
moduleId: module.id,
selector: 'signup',
templateUrl: 'signup.component.html',
styleUrls: ['signup.component.css']
})
export class SignupComponent implements OnInit {
private profileForm:FormGroup;
private validation_errors:Array<any>;
private selectedSkills:Array<string>;
private skillHints:Array<string>;
private skillString:string;
constructor(private route: ActivatedRoute,
private formBuilder: FormBuilder,
private memberService: MemberService,
private router: Router ) {
this.selectedSkills = [];
this.skillHints = [];
this.skillString = '';
// Set up form
this.profileForm = this.formBuilder.group({
skill_string: ['']
});
}
ngOnInit(): any {
// Do something
}
updateSelectedSkills(skillString:string):void {
if(skillString) ) {
let cleanString = skillString.trim().replace(/[ ]{2,}/g, ' ');
this.selectedSkills = _.compact(this.selectedSkills.concat(cleanString.split(',')));
this.skillString = '';
this.skillHints = [];
}
}
skillsHandleEnter(skillString:string):void {
console.log("ENTER");
this.updateSelectedSkills(skillString);
return false;
}
autocompleteSkills(term:string):void {
this.memberService.autocompleteSkills(term).subscribe(
res => {
this.skillHints = [];
for(let i = 0; i < res.data.length; i++) {
this.skillHints.push(res.data[i].name);
}
}
);
}
addSkillFromAutocomplete(skillString:string):void {
this.selectedSkills.push(skillString);
this.memberProfile.skill_string = '';
this.skillHints = [];
this.skillString = '';
}
onSubmit():void {
this.memberService.saveProfile(this.memberProfile, this.selectedSkills).subscribe(
res => {
console.log(res);
}
);
}
}
</code></pre>
| 0debug
|
static inline int get_phys_addr(CPUState *env, uint32_t address,
int access_type, int is_user,
uint32_t *phys_ptr, int *prot,
target_ulong *page_size)
{
if (address < 0x02000000)
address += env->cp15.c13_fcse;
if ((env->cp15.c1_sys & 1) == 0) {
*phys_ptr = address;
*prot = PAGE_READ | PAGE_WRITE;
*page_size = TARGET_PAGE_SIZE;
return 0;
} else if (arm_feature(env, ARM_FEATURE_MPU)) {
*page_size = TARGET_PAGE_SIZE;
return get_phys_addr_mpu(env, address, access_type, is_user, phys_ptr,
prot);
} else if (env->cp15.c1_sys & (1 << 23)) {
return get_phys_addr_v6(env, address, access_type, is_user, phys_ptr,
prot, page_size);
} else {
return get_phys_addr_v5(env, address, access_type, is_user, phys_ptr,
prot, page_size);
}
}
| 1threat
|
Nested arrays in Angular 2 reactive forms? : <p>I have use the following tutorial to create reactive forms in Angular 2 and it works well.</p>
<p><a href="https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2" rel="noreferrer">https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2</a></p>
<p>However, I am now trying to add an array within an array. Using the tutorial above, I have created an 'Organisation' form, which can contain an array of 'Contact' groups. But I am unable to successfully adapt the setup to allow each 'Contact' group to contain an array of 'Email' groups.</p>
<p>I have been unable to find a tutorial or example that covers this and would be grateful for any pointers.</p>
| 0debug
|
dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
enum dshowDeviceType devtype, IBaseFilter **pfilter)
{
struct dshow_ctx *ctx = avctx->priv_data;
IBaseFilter *device_filter = NULL;
IEnumMoniker *classenum = NULL;
IMoniker *m = NULL;
const char *device_name = ctx->device_name[devtype];
int r;
const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
&CLSID_AudioInputDeviceCategory };
const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
(IEnumMoniker **) &classenum, 0);
if (r != S_OK) {
av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
devtypename);
return AVERROR(EIO);
}
while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
IPropertyBag *bag = NULL;
char *buf = NULL;
VARIANT var;
r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
if (r != S_OK)
goto fail1;
var.vt = VT_BSTR;
r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
if (r != S_OK)
goto fail1;
buf = dup_wchar_to_utf8(var.bstrVal);
if (pfilter) {
if (strcmp(device_name, buf))
goto fail1;
IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
} else {
av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);
}
fail1:
if (buf)
av_free(buf);
if (bag)
IPropertyBag_Release(bag);
IMoniker_Release(m);
}
IEnumMoniker_Release(classenum);
if (pfilter) {
if (!device_filter) {
av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
devtypename);
return AVERROR(EIO);
}
*pfilter = device_filter;
}
return 0;
}
| 1threat
|
find_element_by_class_name does not work with python : I am trying to fill out a form, using selenium and python.
I am using find_element_by_class_name in the following code and it is not working. I have no idea why as with java it works...
url='https://service.mail.com/registration.html'
driver = webdriver.Chrome('/Users/xxxxx/code/chromedriver')
driver.get(url)
driver.find_element_by_class_name("Required userdata-firstname").send_keys("james")
Can anyone assist with that? I REALLY do not want to work with java on that.....
| 0debug
|
Firebase hosting with only ONE A record : <p>I have my client's domain registered via 1and1.com </p>
<p>To connect the domain to the Firebase hosting, Firebase asks me to add <em>TWO</em> A records with 2 IPs. In 1and1 we can only add <em>ONE</em> A record. Yesterday Firebase sent me this message by mail </p>
<blockquote>
<p>Please re-verify ownership of www.*******.com on
*******-website. The previous verification for this domain has
been invalidated. You have 1 day to re-verify ownership of
www.*******.com before it is removed from Firebase Hosting,
which will stop all content from being served from the domain. Please
visit the Firebase Hosting Panel to start the re-verification process.</p>
</blockquote>
<p>Today the website was disconnected.</p>
<p>I reconnected the domain to the Firebase hosting through the Firebase control panel and got the website up again. But the Firebase control panel says it still needs setup</p>
<p>I am sure it will disconnect it again soon. How to solve that? (I already called 1and1 and they told me no way I would be able to add another A record.)
<a href="https://i.stack.imgur.com/It6e3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/It6e3.png" alt="enter image description here"></a></p>
| 0debug
|
Issue creating a save as function in python : Im trying to create a function to save data taken from multiple Entry widgets in my code and create a new save file storing the data from all the entries, i made a entry list called entries and try to pull from that but cant get it quite right. It will create the file but its always blank. This is the code for my save as function using tkinter widgets.
def file_save_as(self):
fout = asksaveasfile(mode = 'a', defaultextension = '.txt')
with open('fout', 'a') as f:
for entry in self.entries:
f.write("%s\n" % entry)
| 0debug
|
Date conversion with condition : Please feel free to suggest me to change the title.
I have a hire date column and I want to assign specific Tiers depending on employee work years with the following conditions:
1-4 years = T1
5-9 years = T2
10-15 years = T3
15+ years = T4
For example, if the hire date is 12/07/2002, the tier should equal T4.
10/03/2016 = T1
01/18/2010 = T2
01/14/2006 = T3
12/07/2002 = T4
Is there any way to accomplish this?
Your help will be greatly appreciated.
| 0debug
|
static inline void vc1_pred_mv_intfr(VC1Context *v, int n, int dmv_x, int dmv_y,
int mvn, int r_x, int r_y, uint8_t* is_intra)
{
MpegEncContext *s = &v->s;
int xy, wrap, off = 0;
int A[2], B[2], C[2];
int px, py;
int a_valid = 0, b_valid = 0, c_valid = 0;
int field_a, field_b, field_c;
int total_valid, num_samefield, num_oppfield;
int pos_c, pos_b, n_adj;
wrap = s->b8_stride;
xy = s->block_index[n];
if (s->mb_intra) {
s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = 0;
s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = 0;
s->current_picture.f.motion_val[1][xy][0] = 0;
s->current_picture.f.motion_val[1][xy][1] = 0;
if (mvn == 1) {
s->current_picture.f.motion_val[0][xy + 1][0] = 0;
s->current_picture.f.motion_val[0][xy + 1][1] = 0;
s->current_picture.f.motion_val[0][xy + wrap][0] = 0;
s->current_picture.f.motion_val[0][xy + wrap][1] = 0;
s->current_picture.f.motion_val[0][xy + wrap + 1][0] = 0;
s->current_picture.f.motion_val[0][xy + wrap + 1][1] = 0;
v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
s->current_picture.f.motion_val[1][xy + 1][0] = 0;
s->current_picture.f.motion_val[1][xy + 1][1] = 0;
s->current_picture.f.motion_val[1][xy + wrap][0] = 0;
s->current_picture.f.motion_val[1][xy + wrap][1] = 0;
s->current_picture.f.motion_val[1][xy + wrap + 1][0] = 0;
s->current_picture.f.motion_val[1][xy + wrap + 1][1] = 0;
}
return;
}
off = ((n == 0) || (n == 1)) ? 1 : -1;
if (s->mb_x || (n == 1) || (n == 3)) {
if ((v->blk_mv_type[xy])
|| (!v->blk_mv_type[xy] && !v->blk_mv_type[xy - 1])) {
A[0] = s->current_picture.f.motion_val[0][xy - 1][0];
A[1] = s->current_picture.f.motion_val[0][xy - 1][1];
a_valid = 1;
} else {
A[0] = (s->current_picture.f.motion_val[0][xy - 1][0]
+ s->current_picture.f.motion_val[0][xy - 1 + off * wrap][0] + 1) >> 1;
A[1] = (s->current_picture.f.motion_val[0][xy - 1][1]
+ s->current_picture.f.motion_val[0][xy - 1 + off * wrap][1] + 1) >> 1;
a_valid = 1;
}
if (!(n & 1) && v->is_intra[s->mb_x - 1]) {
a_valid = 0;
A[0] = A[1] = 0;
}
} else
A[0] = A[1] = 0;
B[0] = B[1] = C[0] = C[1] = 0;
if (n == 0 || n == 1 || v->blk_mv_type[xy]) {
if (!s->first_slice_line) {
if (!v->is_intra[s->mb_x - s->mb_stride]) {
b_valid = 1;
n_adj = n | 2;
pos_b = s->block_index[n_adj] - 2 * wrap;
if (v->blk_mv_type[pos_b] && v->blk_mv_type[xy]) {
n_adj = (n & 2) | (n & 1);
}
B[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][0];
B[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][1];
if (v->blk_mv_type[pos_b] && !v->blk_mv_type[xy]) {
B[0] = (B[0] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][0] + 1) >> 1;
B[1] = (B[1] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][1] + 1) >> 1;
}
}
if (s->mb_width > 1) {
if (!v->is_intra[s->mb_x - s->mb_stride + 1]) {
c_valid = 1;
n_adj = 2;
pos_c = s->block_index[2] - 2 * wrap + 2;
if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {
n_adj = n & 2;
}
C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][0];
C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][1];
if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {
C[0] = (1 + C[0] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][0])) >> 1;
C[1] = (1 + C[1] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][1])) >> 1;
}
if (s->mb_x == s->mb_width - 1) {
if (!v->is_intra[s->mb_x - s->mb_stride - 1]) {
c_valid = 1;
n_adj = 3;
pos_c = s->block_index[3] - 2 * wrap - 2;
if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {
n_adj = n | 1;
}
C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][0];
C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][1];
if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {
C[0] = (1 + C[0] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][0]) >> 1;
C[1] = (1 + C[1] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][1]) >> 1;
}
} else
c_valid = 0;
}
}
}
}
} else {
pos_b = s->block_index[1];
b_valid = 1;
B[0] = s->current_picture.f.motion_val[0][pos_b][0];
B[1] = s->current_picture.f.motion_val[0][pos_b][1];
pos_c = s->block_index[0];
c_valid = 1;
C[0] = s->current_picture.f.motion_val[0][pos_c][0];
C[1] = s->current_picture.f.motion_val[0][pos_c][1];
}
total_valid = a_valid + b_valid + c_valid;
if (!s->mb_x && !(n == 1 || n == 3)) {
A[0] = A[1] = 0;
}
if ((s->first_slice_line && v->blk_mv_type[xy]) || (s->first_slice_line && !(n & 2))) {
B[0] = B[1] = C[0] = C[1] = 0;
}
if (!v->blk_mv_type[xy]) {
if (s->mb_width == 1) {
px = B[0];
py = B[1];
} else {
if (total_valid >= 2) {
px = mid_pred(A[0], B[0], C[0]);
py = mid_pred(A[1], B[1], C[1]);
} else if (total_valid) {
if (a_valid) { px = A[0]; py = A[1]; }
if (b_valid) { px = B[0]; py = B[1]; }
if (c_valid) { px = C[0]; py = C[1]; }
} else
px = py = 0;
}
} else {
if (a_valid)
field_a = (A[1] & 4) ? 1 : 0;
else
field_a = 0;
if (b_valid)
field_b = (B[1] & 4) ? 1 : 0;
else
field_b = 0;
if (c_valid)
field_c = (C[1] & 4) ? 1 : 0;
else
field_c = 0;
num_oppfield = field_a + field_b + field_c;
num_samefield = total_valid - num_oppfield;
if (total_valid == 3) {
if ((num_samefield == 3) || (num_oppfield == 3)) {
px = mid_pred(A[0], B[0], C[0]);
py = mid_pred(A[1], B[1], C[1]);
} else if (num_samefield >= num_oppfield) {
px = !field_a ? A[0] : B[0];
py = !field_a ? A[1] : B[1];
} else {
px = field_a ? A[0] : B[0];
py = field_a ? A[1] : B[1];
}
} else if (total_valid == 2) {
if (num_samefield >= num_oppfield) {
if (!field_a && a_valid) {
px = A[0];
py = A[1];
} else if (!field_b && b_valid) {
px = B[0];
py = B[1];
} else if (c_valid) {
px = C[0];
py = C[1];
} else px = py = 0;
} else {
if (field_a && a_valid) {
px = A[0];
py = A[1];
} else if (field_b && b_valid) {
px = B[0];
py = B[1];
} else if (c_valid) {
px = C[0];
py = C[1];
} else px = py = 0;
}
} else if (total_valid == 1) {
px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);
py = (a_valid) ? A[1] : ((b_valid) ? B[1] : C[1]);
} else
px = py = 0;
}
s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;
s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = ((py + dmv_y + r_y) & ((r_y << 1) - 1)) - r_y;
if (mvn == 1) {
s->current_picture.f.motion_val[0][xy + 1 ][0] = s->current_picture.f.motion_val[0][xy][0];
s->current_picture.f.motion_val[0][xy + 1 ][1] = s->current_picture.f.motion_val[0][xy][1];
s->current_picture.f.motion_val[0][xy + wrap ][0] = s->current_picture.f.motion_val[0][xy][0];
s->current_picture.f.motion_val[0][xy + wrap ][1] = s->current_picture.f.motion_val[0][xy][1];
s->current_picture.f.motion_val[0][xy + wrap + 1][0] = s->current_picture.f.motion_val[0][xy][0];
s->current_picture.f.motion_val[0][xy + wrap + 1][1] = s->current_picture.f.motion_val[0][xy][1];
} else if (mvn == 2) {
s->current_picture.f.motion_val[0][xy + 1][0] = s->current_picture.f.motion_val[0][xy][0];
s->current_picture.f.motion_val[0][xy + 1][1] = s->current_picture.f.motion_val[0][xy][1];
s->mv[0][n + 1][0] = s->mv[0][n][0];
s->mv[0][n + 1][1] = s->mv[0][n][1];
}
}
| 1threat
|
How to configure "git pull --ff-only" and "git merge --no-ff" : <p>A typical git workflow for me is to clone a remote repository and use git pull to keep it up-to-date. I don't want merge commits when I pull, so i use the --ff-only option.</p>
<p>I also make local branches for feature work. I want to preserve the branch history, so when I merge the local branch back to my local clone, I use the --no-ff option.</p>
<p>How can I configure git to use those options by default? Currently my .gitconfig looks like this:</p>
<pre><code>[merge]
ff = false
[pull]
ff = only
</code></pre>
<p>However, git pull (which is really git fetch and git merge) seems to be picking up the merge option and therefore creating merge.</p>
| 0debug
|
Iterate on arry of json objects in go : I just started learning Go and trying to iterate through each element of array of json objects.
I tried the following.
package main
import (
"encoding/json"
"fmt"
)
type itemdata []string
func main() {
var birds itemdata
birdJson := `[{"species":"pigeon","decription":"likes to perch on rocks"},{"species":"eagle","description":"bird of prey"},{"species":"eagle","description":"bird of prey"}]`
json.Unmarshal([]byte(birdJson), &birds)
fmt.Println(len(birds))
fmt.Println(birds)
for i := range birds {
fmt.Println(i)
fmt.Println(bird)
}
}
How can I iterate on each json objects?
Expected Output:
0
{"species":"pigeon","decription":"likes to perch on rocks"}
1
{"species":"eagle","description":"bird of prey"}
2
{"species":"eagle","description":"bird of prey"}
| 0debug
|
int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count)
{
int i, av_uninit(j);
int current_ref_assigned = 0, err = 0;
H264Picture *av_uninit(pic);
if ((h->avctx->debug & FF_DEBUG_MMCO) && mmco_count == 0)
av_log(h->avctx, AV_LOG_DEBUG, "no mmco here\n");
for (i = 0; i < mmco_count; i++) {
int av_uninit(structure), av_uninit(frame_num);
if (h->avctx->debug & FF_DEBUG_MMCO)
av_log(h->avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode,
h->mmco[i].short_pic_num, h->mmco[i].long_arg);
if (mmco[i].opcode == MMCO_SHORT2UNUSED ||
mmco[i].opcode == MMCO_SHORT2LONG) {
frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
pic = find_short(h, frame_num, &j);
if (!pic) {
if (mmco[i].opcode != MMCO_SHORT2LONG ||
!h->long_ref[mmco[i].long_arg] ||
h->long_ref[mmco[i].long_arg]->frame_num != frame_num) {
av_log(h->avctx, AV_LOG_ERROR, "mmco: unref short failure\n");
err = AVERROR_INVALIDDATA;
}
continue;
}
}
switch (mmco[i].opcode) {
case MMCO_SHORT2UNUSED:
if (h->avctx->debug & FF_DEBUG_MMCO)
av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n",
h->mmco[i].short_pic_num, h->short_ref_count);
remove_short(h, frame_num, structure ^ PICT_FRAME);
break;
case MMCO_SHORT2LONG:
if (h->long_ref[mmco[i].long_arg] != pic)
remove_long(h, mmco[i].long_arg, 0);
remove_short_at_index(h, j);
h->long_ref[ mmco[i].long_arg ] = pic;
if (h->long_ref[mmco[i].long_arg]) {
h->long_ref[mmco[i].long_arg]->long_ref = 1;
h->long_ref_count++;
}
break;
case MMCO_LONG2UNUSED:
j = pic_num_extract(h, mmco[i].long_arg, &structure);
pic = h->long_ref[j];
if (pic) {
remove_long(h, j, structure ^ PICT_FRAME);
} else if (h->avctx->debug & FF_DEBUG_MMCO)
av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
break;
case MMCO_LONG:
if (h->short_ref[0] == h->cur_pic_ptr)
remove_short_at_index(h, 0);
if (h->cur_pic_ptr->long_ref) {
for (j = 0; j < FF_ARRAY_ELEMS(h->long_ref); j++) {
if (h->long_ref[j] == h->cur_pic_ptr)
remove_long(h, j, 0);
}
}
if (h->long_ref[mmco[i].long_arg] != h->cur_pic_ptr) {
remove_long(h, mmco[i].long_arg, 0);
h->long_ref[mmco[i].long_arg] = h->cur_pic_ptr;
h->long_ref[mmco[i].long_arg]->long_ref = 1;
h->long_ref_count++;
}
h->cur_pic_ptr->reference |= h->picture_structure;
current_ref_assigned = 1;
break;
case MMCO_SET_MAX_LONG:
assert(mmco[i].long_arg <= 16);
for (j = mmco[i].long_arg; j < 16; j++) {
remove_long(h, j, 0);
}
break;
case MMCO_RESET:
while (h->short_ref_count) {
remove_short(h, h->short_ref[0]->frame_num, 0);
}
for (j = 0; j < 16; j++) {
remove_long(h, j, 0);
}
h->frame_num = h->cur_pic_ptr->frame_num = 0;
h->mmco_reset = 1;
h->cur_pic_ptr->mmco_reset = 1;
break;
default: assert(0);
}
}
if (!current_ref_assigned) {
if (h->short_ref_count && h->short_ref[0] == h->cur_pic_ptr) {
h->cur_pic_ptr->reference = PICT_FRAME;
} else if (h->cur_pic_ptr->long_ref) {
av_log(h->avctx, AV_LOG_ERROR, "illegal short term reference "
"assignment for second field "
"in complementary field pair "
"(first field is long term)\n");
err = AVERROR_INVALIDDATA;
} else {
pic = remove_short(h, h->cur_pic_ptr->frame_num, 0);
if (pic) {
av_log(h->avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
err = AVERROR_INVALIDDATA;
}
if (h->short_ref_count)
memmove(&h->short_ref[1], &h->short_ref[0],
h->short_ref_count * sizeof(H264Picture*));
h->short_ref[0] = h->cur_pic_ptr;
h->short_ref_count++;
h->cur_pic_ptr->reference |= h->picture_structure;
}
}
if (h->long_ref_count + h->short_ref_count -
(h->short_ref[0] == h->cur_pic_ptr) > h->sps.ref_frame_count) {
av_log(h->avctx, AV_LOG_ERROR,
"number of reference frames (%d+%d) exceeds max (%d; probably "
"corrupt input), discarding one\n",
h->long_ref_count, h->short_ref_count, h->sps.ref_frame_count);
err = AVERROR_INVALIDDATA;
if (h->long_ref_count && !h->short_ref_count) {
for (i = 0; i < 16; ++i)
if (h->long_ref[i])
break;
assert(i < 16);
remove_long(h, i, 0);
} else {
pic = h->short_ref[h->short_ref_count - 1];
remove_short(h, pic->frame_num, 0);
}
}
print_short_term(h);
print_long_term(h);
return (h->avctx->err_recognition & AV_EF_EXPLODE) ? err : 0;
}
| 1threat
|
db.execute('SELECT * FROM employees WHERE id = ' + user_input)
| 1threat
|
RxJs: poll until interval done or correct data received : <p>How do i execute the following scenario in the browser with RxJs:</p>
<ul>
<li>submit data to queue for processing</li>
<li>get back the job id</li>
<li>poll another endpoint every 1s until result is available or 60seconds have passed(then fail)</li>
</ul>
<p>Intermediate solution that i've come up with:</p>
<pre><code> Rx.Observable
.fromPromise(submitJobToQueue(jobData))
.flatMap(jobQueueData =>
Rx.Observable
.interval(1000)
.delay(5000)
.map(_ => jobQueueData.jobId)
.take(55)
)
.flatMap(jobId => Rx.Observable.fromPromise(pollQueueForResult(jobId)))
.filter(result => result.completed)
.subscribe(
result => console.log('Result', result),
error => console.log('Error', error)
);
</code></pre>
<ol>
<li>Is there a way without intermediate variables to stop the timer once the data arrives or error occurs? I now i could introduce new observable and then use <code>takeUntil</code></li>
<li>Is <code>flatMap</code> usage here semantically correct? Maybe this whole thing should be rewritten and not chained with <code>flatMap</code> ?</li>
</ol>
| 0debug
|
how to make program code for application that can calculate postage of goods with android app : [See image][1]
i learning make a application, the application have function to calculate postage of goods from a airport of origin to airport destination
the process description is as follows:
1. choose a airport origin
2. then,choose airport of destination
3. fill actual weight
4. choose a commodity from spinner
5. choose a airline
6. klik CALCULATE button to get postage
7. Postage will be show below of CALCULATE button
What technique will i use to get the postage, is it using SWITCH CASE or IF ?, please give me a reference. I am very happy for your help
[1]: https://i.stack.imgur.com/xuB7F.png
| 0debug
|
bluebird.js vs bluebird.core.js what is the difference? : <p>What is the difference between bluebird.js and bluebird.core.js? </p>
<p>When should I use bluebird.core.js instead of bluebird.js? </p>
<p>I haven't been able to find anything in the <a href="http://bluebirdjs.com/docs/getting-started.html">bluebird site</a> or elsewhere.</p>
| 0debug
|
Vertical aligning a <span> text in a header in React : <p>I have a react header component that looks like this:</p>
<pre><code>const Header = () => {
return (
<div className="navbar">
<div className="logo-container">
<img id='logo' alt='header-logo' src={Logo}/><span id="header-title">Dashboard</span>
</div>
</div>
);
}
export default Header;
</code></pre>
<p>The stylesheet for this component looks like</p>
<pre><code>.navbar {
height: 4em;
background-color: #f9f9f9;
width: 100%;
background: #00bceb;
}
#logo {
margin-left: 2em
}
#header-title {
display: inline-block;
vertical-align: middle;
margin-left: 0.5em;
color: #f9f9f9;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/VpGf3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VpGf3.png" alt="enter image description here"></a></p>
<p>(I'm hiding the logo)</p>
<p>The text is not middle aligned.</p>
<p>Any help?</p>
| 0debug
|
kafka broker not available at starting : <p>I set on a ubuntu node of a cluster a kafka 0.11.0.0 instance.
Until some weeks ago everything worked fine, today I'm trying to starting it and I obtain this error after the boot:</p>
<pre><code>[2017-09-11 16:21:13,894] INFO [Kafka Server 0], started (kafka.server.KafkaServer)
[2017-09-11 16:21:18,998] WARN Connection to node 0 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2017-09-11 16:21:21,991] WARN Connection to node 0 could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
... and so on...
</code></pre>
<p>My server.properties:</p>
<pre><code>############################# Server Basics #############################
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0
# Switch to enable topic deletion or not, default value is false
delete.topic.enable=true
############################# Socket Server Settings ##########################$
# The address the socket server listens on. It will get the value returned from
# java.net.InetAddress.getCanonicalHostName() if not configured.
# FORMAT:
# listeners = listener_name://host_name:port
# EXAMPLE:
# listeners = PLAINTEXT://your.host.name:9092
#listeners=PLAINTEXT://9092
# Hostname and port the broker will advertise to producers and consumers. If no$
# it uses the value for "listeners" if configured. Otherwise, it will use the $
# returned from java.net.InetAddress.getCanonicalHostName().
advertised.listeners=PLAINTEXT://hidden_ip:55091
</code></pre>
<p>I edited advertised.listeners because there is a proxy to redirect requests to the broker. Anyway until some weeks ago everything worked fine...</p>
<p>My step to start kafka:</p>
<pre><code>1- service zookeeper start
2- ./kafka_2.11-0.11.0.0/bin/kafka-server-start.sh ~/kafka_2.11-0.11.0.0/config/server.properties
</code></pre>
<p>Any advises?
Thank you</p>
| 0debug
|
C++ Class won't execute function : <p>I want to write a simple backup program. Its not finished yet, but i've encountered a problem: My class responsible for setting the right path wont execute the worker which will copy the file. I don't know why and yes - i already looked up on any helping site i know. Here is my filecopy h code:</p>
<pre><code>#ifndef __FILECOPY_H_INCLUDED__
#define __FILECOPY_H_INCLUDED__
#include<iostream>
#include<fstream>
#include<ctime>
class filecopy
{
std::string dest_path;
std::string src_path;
public:
filecopy(std::string, std::string);
void filecopy_worker()
{
std::cout << "FILECOPY PROCESS STARTED" << std::endl;
std::ifstream source(src_path);
std::ofstream dest(dest_path);
dest << source.rdbuf();
source.close();
dest.close();
}
};
filecopy::filecopy(std::string a, std::string b)
{
dest_path = a;
src_path = b;
}
#endif
</code></pre>
<p>And here my main.cpp code:</p>
<pre><code>#include<iostream>
#include<stdlib.h>
#include"filecopy.h"
int main(int argc, char *argv[])
{
if(argc != 3)
{
std::cout << "USAGE: " << argv[0] << " <filesource>" << std::endl;
return 1;
}
else
{
filecopy target1(argv[2], argv[1]);
std::cout << "TARGET ASSIGNED" << std::endl;
std::cout << "EXECUTE FILEWORKER" << std::endl;
}
return 0;
}
</code></pre>
| 0debug
|
Android Studio Install Disappears : <p>I'm trying to install the latest Android Studio.</p>
<p>Environment:</p>
<p>Windows7 64-bit
JDK v12</p>
<p>I run the installer, and then it disappears after the initial setup progress dialog. Is there any way to troubleshoot this?</p>
<p><a href="https://youtu.be/y1ueVCxyhdo" rel="nofollow noreferrer">Video of the install is here</a></p>
| 0debug
|
React-navigation: Deep linking with authentication : <p>I am building a mobile app with react-native and the react-navigation library for managing the navigation in my app. Right now, my app looks something like that:</p>
<pre><code>App [SwitchNavigator]
Splash [Screen]
Auth [Screen]
MainApp [StackNavigator]
Home [Screen] (/home)
Profile [Screen] (/profile)
Notifications [Screen] (/notifications)
</code></pre>
<p>I have integrated Deep Linking with the patterns above for the screens <code>Home</code>, <code>Profile</code> and <code>Notifications</code>, and it works as expected. The issue I am facing is how to manage my user's authentication when using a deep link. Right now whenever I open a deep link (<code>myapp://profile</code> for instance) the app takes me on the screen whether or not I am authenticated. What I would want it to do is to check before in <code>AsyncStorage</code> if there is a <code>userToken</code> and if there isn't or it is not valid anymore then just redirect on the <code>Auth</code> screen.</p>
<p>I set up the authentication flow in almost exactly the same way as described <a href="https://reactnavigation.org/docs/en/auth-flow.html" rel="noreferrer">here</a>. So when my application starts the <code>Splash</code> screen checks in the user's phone if there is a valid token and sends him either on the <code>Auth</code> screen or <code>Home</code> screen.</p>
<p>The only solution I have come up with for now is to direct every deep link to <code>Splash</code>, authentify my user, and then parse the link to navigate to the good screen.
So for example when a user opens <code>myapp://profile</code>, I open the app on <code>Splash</code>, validate the token, then parse the url (<code>/profile</code>), and finally redirect either to <code>Auth</code> or <code>Profile</code>.</p>
<p>Is that the good way to do so, or does react-navigation provide a better way to do this ? The <a href="https://reactnavigation.org/docs/en/deep-linking.html" rel="noreferrer">Deep linking</a> page on their website is a little light.</p>
<p>Thanks for the help !</p>
| 0debug
|
void qemu_cpu_kick(void *_env)
{
CPUState *env = _env;
qemu_cond_broadcast(env->halt_cond);
if (!env->thread_kicked) {
qemu_cpu_kick_thread(env);
env->thread_kicked = true;
}
}
| 1threat
|
How can the nested loops of unknown layers be implemented by recursion? : <p>int m =10;</p>
<pre><code> int n = 9;
int p = 4;
int q = 7;
for(int i=0;i<m;i++){
int a = i;
for(int j=0;j<n;j++){
int b = j;
if(b==a){
continue;
}
for(int k=0;k<p;k++){
int c = k;
if(c==b || c==a){
continue;
}
for(int l=0;l<q;l++){
int d = l;
if(d==c || d==b || d==a){
continue;
}
System.out.println("i="+i+",j="+j+",k="+k+",l="+l);
}
}
}
}
</code></pre>
<p>For example, the code fragment is a four layer nested loop, and the loop between has data dependencies, and nested layers is uncertain, how it will achieve through the recursive (nested is uncertain)?</p>
| 0debug
|
Jquery - Get all the option fields of a select and save the value and id and compare with var string and is inside : I have a select with several option, each option has an id and the value.
This select is loaded with an ajax in jquery.
There is also a string variable that contains a text, with which you would have to compare all the option values and if any of them are within this text, select the option value as selected.
Example:
var mytexto = 'Ipad Mini 4 16GB/1GB Azul';
<select id="nombre_modelo" class="form-control">
<option value="" disabled="disabled" selected="selected">Select one model name</option>
<option id="25">Ipad 3</option>
<option id="26">Ipad 4</option>
<option id="27">Mini 4</option>
<option id="28">Mini Wifi A1403</option>
<option id="29">Mini Wifi A1432</option>
</select>
In this example you would have to get the id = '27 'and the value =' Mini 4 'of "<option id="27"> Mini 4</option>" which is the one inside the string.
How do I get these two values, the id and the value?
| 0debug
|
Passing value by refrence : can some one explain completely that what is the this?????
struct p{
int x;
int y;
struct p *ptr;
};
I can't understand the line that we again write struct p.
| 0debug
|
Odd element transfer (Arrays) : this.blockHeights = new int[] { 1, 2, 1, 1, 2, 1, 2, 1 };
int x = blockHeights.length/2;
int leftSource[] = new int[x];
System.out.println(x);
int j = 0;
for (int i = 0; i < x; i++)
{
if ((blockHeights[i]%2 == 0) || (i == 0)) //odd-elements
{
leftSource[i] = blockHeights[i];
}
}
for (int i = 0; i < leftSource.length; i++)
{
System.out.println(leftSource[i]);
}
The output is 1, 2, 0, 0. Whereas my goal is to print out 1st, 3rd, 5th and 7th element from array blockHeights and put it in new array leftSource.
| 0debug
|
Access strings which is inside the list : Python list has ['12:30','12:45'] and I want to access the '12:30' for the first iteration and the second iteration I should get '12:45'
my_list=['12:30','12:45']
for each_value in my_list:
print(each_value[0])
my_list=['12:30','12:45']
for each_value in my_list:
print(each_value[0])
The expected result is '12:30' but the acutal output is '1'
| 0debug
|
static void mkv_write_simpletag(AVIOContext *pb, AVDictionaryEntry *t)
{
uint8_t *key = av_strdup(t->key);
uint8_t *p = key;
const uint8_t *lang = NULL;
ebml_master tag;
if ((p = strrchr(p, '-')) &&
(lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
*p = 0;
p = key;
while (*p) {
if (*p == ' ')
*p = '_';
else if (*p >= 'a' && *p <= 'z')
*p -= 'a' - 'A';
p++;
}
tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
if (lang)
put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
end_ebml_master(pb, tag);
av_freep(&key);
}
| 1threat
|
static int adpcm_decode_frame(AVCodecContext *avctx,
void *data, int *data_size,
uint8_t *buf, int buf_size)
{
ADPCMContext *c = avctx->priv_data;
ADPCMChannelStatus *cs;
int n, m, channel, i;
int block_predictor[2];
short *samples;
short *samples_end;
uint8_t *src;
int st;
unsigned char last_byte = 0;
unsigned char nibble;
int decode_top_nibble_next = 0;
int diff_channel;
uint32_t samples_in_chunk;
int32_t previous_left_sample, previous_right_sample;
int32_t current_left_sample, current_right_sample;
int32_t next_left_sample, next_right_sample;
int32_t coeff1l, coeff2l, coeff1r, coeff2r;
uint8_t shift_left, shift_right;
int count1, count2;
if (!buf_size)
return 0;
if(*data_size/4 < buf_size + 8)
return -1;
samples = data;
samples_end= samples + *data_size/2;
*data_size= 0;
src = buf;
st = avctx->channels == 2 ? 1 : 0;
switch(avctx->codec->id) {
case CODEC_ID_ADPCM_IMA_QT:
n = (buf_size - 2);
channel = c->channel;
cs = &(c->status[channel]);
cs->predictor = (*src++) << 8;
cs->predictor |= (*src & 0x80);
cs->predictor &= 0xFF80;
if(cs->predictor & 0x8000)
cs->predictor -= 0x10000;
CLAMP_TO_SHORT(cs->predictor);
cs->step_index = (*src++) & 0x7F;
if (cs->step_index > 88){
av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
cs->step_index = 88;
}
cs->step = step_table[cs->step_index];
if (st && channel)
samples++;
for(m=32; n>0 && m>0; n--, m--) {
*samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);
samples += avctx->channels;
*samples = adpcm_ima_expand_nibble(cs, (src[0] >> 4) & 0x0F, 3);
samples += avctx->channels;
src ++;
}
if(st) {
c->channel = (channel + 1) % 2;
if(channel == 1) {
return src - buf;
}
}
break;
case CODEC_ID_ADPCM_IMA_WAV:
if (avctx->block_align != 0 && buf_size > avctx->block_align)
buf_size = avctx->block_align;
samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;
for(i=0; i<avctx->channels; i++){
cs = &(c->status[i]);
cs->predictor = (int16_t)(src[0] + (src[1]<<8));
src+=2;
XXX: is this correct ??: *samples++ = cs->predictor;
cs->step_index = *src++;
if (cs->step_index > 88){
av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
cs->step_index = 88;
}
if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]);
}
while(src < buf + buf_size){
for(m=0; m<4; m++){
for(i=0; i<=st; i++)
*samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);
for(i=0; i<=st; i++)
*samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4 , 3);
src++;
}
src += 4*st;
}
break;
case CODEC_ID_ADPCM_4XM:
cs = &(c->status[0]);
c->status[0].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;
if(st){
c->status[1].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;
}
c->status[0].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;
if(st){
c->status[1].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;
}
if (cs->step_index < 0) cs->step_index = 0;
if (cs->step_index > 88) cs->step_index = 88;
m= (buf_size - (src - buf))>>st;
for(i=0; i<m; i++) {
*samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);
if (st)
*samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);
*samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);
if (st)
*samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);
}
src += m<<st;
break;
case CODEC_ID_ADPCM_MS:
if (avctx->block_align != 0 && buf_size > avctx->block_align)
buf_size = avctx->block_align;
n = buf_size - 7 * avctx->channels;
if (n < 0)
return -1;
block_predictor[0] = av_clip(*src++, 0, 7);
block_predictor[1] = 0;
if (st)
block_predictor[1] = av_clip(*src++, 0, 7);
c->status[0].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
src+=2;
if (st){
c->status[1].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
src+=2;
}
c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];
c->status[0].coeff2 = AdaptCoeff2[block_predictor[0]];
c->status[1].coeff1 = AdaptCoeff1[block_predictor[1]];
c->status[1].coeff2 = AdaptCoeff2[block_predictor[1]];
c->status[0].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
src+=2;
if (st) c->status[1].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
if (st) src+=2;
c->status[0].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
src+=2;
if (st) c->status[1].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
if (st) src+=2;
*samples++ = c->status[0].sample1;
if (st) *samples++ = c->status[1].sample1;
*samples++ = c->status[0].sample2;
if (st) *samples++ = c->status[1].sample2;
for(;n>0;n--) {
*samples++ = adpcm_ms_expand_nibble(&c->status[0], (src[0] >> 4) & 0x0F);
*samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);
src ++;
}
break;
case CODEC_ID_ADPCM_IMA_DK4:
if (avctx->block_align != 0 && buf_size > avctx->block_align)
buf_size = avctx->block_align;
c->status[0].predictor = (int16_t)(src[0] | (src[1] << 8));
c->status[0].step_index = src[2];
src += 4;
*samples++ = c->status[0].predictor;
if (st) {
c->status[1].predictor = (int16_t)(src[0] | (src[1] << 8));
c->status[1].step_index = src[2];
src += 4;
*samples++ = c->status[1].predictor;
}
while (src < buf + buf_size) {
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F, 3);
if (st)
*samples++ = adpcm_ima_expand_nibble(&c->status[1],
src[0] & 0x0F, 3);
else
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
src[0] & 0x0F, 3);
src++;
}
break;
case CODEC_ID_ADPCM_IMA_DK3:
if (avctx->block_align != 0 && buf_size > avctx->block_align)
buf_size = avctx->block_align;
if(buf_size + 16 > (samples_end - samples)*3/8)
return -1;
c->status[0].predictor = (int16_t)(src[10] | (src[11] << 8));
c->status[1].predictor = (int16_t)(src[12] | (src[13] << 8));
c->status[0].step_index = src[14];
c->status[1].step_index = src[15];
src += 16;
diff_channel = c->status[1].predictor;
while (1) {
DK3_GET_NEXT_NIBBLE();
adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
DK3_GET_NEXT_NIBBLE();
adpcm_ima_expand_nibble(&c->status[1], nibble, 3);
diff_channel = (diff_channel + c->status[1].predictor) / 2;
*samples++ = c->status[0].predictor + c->status[1].predictor;
*samples++ = c->status[0].predictor - c->status[1].predictor;
DK3_GET_NEXT_NIBBLE();
adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
diff_channel = (diff_channel + c->status[1].predictor) / 2;
*samples++ = c->status[0].predictor + c->status[1].predictor;
*samples++ = c->status[0].predictor - c->status[1].predictor;
}
break;
case CODEC_ID_ADPCM_IMA_WS:
while (src < buf + buf_size) {
if (st) {
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F, 3);
*samples++ = adpcm_ima_expand_nibble(&c->status[1],
src[0] & 0x0F, 3);
} else {
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F, 3);
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
src[0] & 0x0F, 3);
}
src++;
}
break;
case CODEC_ID_ADPCM_XA:
c->status[0].sample1 = c->status[0].sample2 =
c->status[1].sample1 = c->status[1].sample2 = 0;
while (buf_size >= 128) {
xa_decode(samples, src, &c->status[0], &c->status[1],
avctx->channels);
src += 128;
samples += 28 * 8;
buf_size -= 128;
}
break;
case CODEC_ID_ADPCM_EA:
samples_in_chunk = AV_RL32(src);
if (samples_in_chunk >= ((buf_size - 12) * 2)) {
src += buf_size;
break;
}
src += 4;
current_left_sample = (int16_t)AV_RL16(src);
src += 2;
previous_left_sample = (int16_t)AV_RL16(src);
src += 2;
current_right_sample = (int16_t)AV_RL16(src);
src += 2;
previous_right_sample = (int16_t)AV_RL16(src);
src += 2;
for (count1 = 0; count1 < samples_in_chunk/28;count1++) {
coeff1l = ea_adpcm_table[(*src >> 4) & 0x0F];
coeff2l = ea_adpcm_table[((*src >> 4) & 0x0F) + 4];
coeff1r = ea_adpcm_table[*src & 0x0F];
coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];
src++;
shift_left = ((*src >> 4) & 0x0F) + 8;
shift_right = (*src & 0x0F) + 8;
src++;
for (count2 = 0; count2 < 28; count2++) {
next_left_sample = (((*src & 0xF0) << 24) >> shift_left);
next_right_sample = (((*src & 0x0F) << 28) >> shift_right);
src++;
next_left_sample = (next_left_sample +
(current_left_sample * coeff1l) +
(previous_left_sample * coeff2l) + 0x80) >> 8;
next_right_sample = (next_right_sample +
(current_right_sample * coeff1r) +
(previous_right_sample * coeff2r) + 0x80) >> 8;
CLAMP_TO_SHORT(next_left_sample);
CLAMP_TO_SHORT(next_right_sample);
previous_left_sample = current_left_sample;
current_left_sample = next_left_sample;
previous_right_sample = current_right_sample;
current_right_sample = next_right_sample;
*samples++ = (unsigned short)current_left_sample;
*samples++ = (unsigned short)current_right_sample;
}
}
break;
case CODEC_ID_ADPCM_IMA_SMJPEG:
c->status[0].predictor = *src;
src += 2;
c->status[0].step_index = *src++;
src++;
while (src < buf + buf_size) {
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
*src & 0x0F, 3);
*samples++ = adpcm_ima_expand_nibble(&c->status[0],
(*src >> 4) & 0x0F, 3);
src++;
}
break;
case CODEC_ID_ADPCM_CT:
while (src < buf + buf_size) {
if (st) {
*samples++ = adpcm_ct_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F);
*samples++ = adpcm_ct_expand_nibble(&c->status[1],
src[0] & 0x0F);
} else {
*samples++ = adpcm_ct_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F);
*samples++ = adpcm_ct_expand_nibble(&c->status[0],
src[0] & 0x0F);
}
src++;
}
break;
case CODEC_ID_ADPCM_SBPRO_4:
case CODEC_ID_ADPCM_SBPRO_3:
case CODEC_ID_ADPCM_SBPRO_2:
if (!c->status[0].step_index) {
*samples++ = 128 * (*src++ - 0x80);
if (st)
*samples++ = 128 * (*src++ - 0x80);
c->status[0].step_index = 1;
}
if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {
while (src < buf + buf_size) {
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F, 4, 0);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
src[0] & 0x0F, 4, 0);
src++;
}
} else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {
while (src < buf + buf_size && samples + 2 < samples_end) {
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
(src[0] >> 5) & 0x07, 3, 0);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
(src[0] >> 2) & 0x07, 3, 0);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
src[0] & 0x03, 2, 0);
src++;
}
} else {
while (src < buf + buf_size && samples + 3 < samples_end) {
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
(src[0] >> 6) & 0x03, 2, 2);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
(src[0] >> 4) & 0x03, 2, 2);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
(src[0] >> 2) & 0x03, 2, 2);
*samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
src[0] & 0x03, 2, 2);
src++;
}
}
break;
case CODEC_ID_ADPCM_SWF:
{
GetBitContext gb;
const int *table;
int k0, signmask, nb_bits;
int size = buf_size*8;
init_get_bits(&gb, buf, size);
read bits & inital values
nb_bits = get_bits(&gb, 2)+2;
av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);
table = swf_index_tables[nb_bits-2];
k0 = 1 << (nb_bits-2);
signmask = 1 << (nb_bits-1);
for (i = 0; i < avctx->channels; i++) {
*samples++ = c->status[i].predictor = get_sbits(&gb, 16);
c->status[i].step_index = get_bits(&gb, 6);
}
while (get_bits_count(&gb) < size)
{
int i;
for (i = 0; i < avctx->channels; i++) {
similar to IMA adpcm
int delta = get_bits(&gb, nb_bits);
int step = step_table[c->status[i].step_index];
long vpdiff = 0; vpdiff = (delta+0.5)*step/4
int k = k0;
do {
if (delta & k)
vpdiff += step;
step >>= 1;
k >>= 1;
} while(k);
vpdiff += step;
if (delta & signmask)
c->status[i].predictor -= vpdiff;
else
c->status[i].predictor += vpdiff;
c->status[i].step_index += table[delta & (~signmask)];
c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);
c->status[i].predictor = av_clip(c->status[i].predictor, -32768, 32767);
*samples++ = c->status[i].predictor;
if (samples >= samples_end) {
av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
return -1;
}
}
}
src += buf_size;
break;
}
case CODEC_ID_ADPCM_YAMAHA:
while (src < buf + buf_size) {
if (st) {
*samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
src[0] & 0x0F);
*samples++ = adpcm_yamaha_expand_nibble(&c->status[1],
(src[0] >> 4) & 0x0F);
} else {
*samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
src[0] & 0x0F);
*samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
(src[0] >> 4) & 0x0F);
}
src++;
}
break;
case CODEC_ID_ADPCM_THP:
{
int table[2][16];
unsigned int samplecnt;
int prev[2][2];
int ch;
if (buf_size < 80) {
av_log(avctx, AV_LOG_ERROR, "frame too small\n");
return -1;
}
src+=4;
samplecnt = bytestream_get_be32(&src);
for (i = 0; i < 32; i++)
table[0][i] = (int16_t)bytestream_get_be16(&src);
for (i = 0; i < 4; i++)
prev[0][i] = (int16_t)bytestream_get_be16(&src);
if (samplecnt >= (samples_end - samples) / (st + 1)) {
av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
return -1;
}
for (ch = 0; ch <= st; ch++) {
samples = (unsigned short *) data + ch;
for (i = 0; i < samplecnt / 14; i++) {
int index = (*src >> 4) & 7;
unsigned int exp = 28 - (*src++ & 15);
int factor1 = table[ch][index * 2];
int factor2 = table[ch][index * 2 + 1];
for (n = 0; n < 14; n++) {
int32_t sampledat;
if(n&1) sampledat= *src++ <<28;
else sampledat= (*src&0xF0)<<24;
*samples = ((prev[ch][0]*factor1
+ prev[ch][1]*factor2) >> 11) + (sampledat>>exp);
prev[ch][1] = prev[ch][0];
prev[ch][0] = *samples++;
samples += st;
}
}
}
samples -= st;
break;
}
default:
return -1;
}
*data_size = (uint8_t *)samples - (uint8_t *)data;
return src - buf;
}
| 1threat
|
How to save secret key securely in android : <p>I just read this article <a href="http://android-developers.blogspot.in/2013/02/using-cryptography-to-store-credentials.html" rel="noreferrer">http://android-developers.blogspot.in/2013/02/using-cryptography-to-store-credentials.html</a> where I learnt to generate security key.</p>
<p>I want to know how to save this generated key securely so hackers wont get this even phone is rooted.</p>
<p>If we save this <code>SharedPreference</code>, <code>Storage</code> then hacker can get this.</p>
<p>Thanks.</p>
| 0debug
|
C# Syntax beyond me, a beginner : <p>Okay, so still very new to C#, so sorry if this is obvious...</p>
<p>There is some code I can't follow that was created by someone who is much better at C#than I am.</p>
<p>We have a class, call it "CC", and it has a number of fields, one of which is "FORM_NBR".</p>
<p>So, in a nutshell:</p>
<pre><code>public class CC
{
public CC();
//Many, many fields...
...
public long FORM_NBR { get; set; }
...
}
</code></pre>
<p>At some point, an object is created...</p>
<pre><code>CC c = new CC();
</code></pre>
<p>and then this line is called:</p>
<pre><code>c.FORM_NBR = c.FORM_NBR.GetCheckDigit(' ');
</code></pre>
<p>Now, there is this function deep in the library we inherited:</p>
<pre><code>public static short GetCheckDigit(this long nFormNbr, char chFormTypCd)
{
short nCkDgt = 0; // Default to 0
switch (chFormTypCd)
{
//Many, many cases...
...
default:
nCkDgt = CalculateCheckDigit(nFormNbr);
break;
}
return nCkDgt;
}
</code></pre>
<p>My question is this. Being new-ish to C#, how is GetCheckDigit getting called from a long? What is this syntax?</p>
<p>I don't even know how I would describe/google this!</p>
| 0debug
|
Reducing array to simple format : I have array of
[
0: "United States"
1: "India"
2: "Germany"
3: "Brazil"
4: "Taiwan"
5: "Israel"
6: "United Kingdom"
]
I just want to make it like
["United States", "India", "Germany".....]
I already tried some codes like
> .reduce(), .flat(), or .concat()
but still not working
| 0debug
|
START_TEST(unterminated_string)
{
QObject *obj = qobject_from_json("\"abc");
fail_unless(obj == NULL);
}
| 1threat
|
Ruby simple bar graph challenge using arrays : I am really new to Ruby and am trying to solve the following challenge, which is to create a simple bar graph program using Ruby:
[Challenge picture][1]
[1]: https://i.stack.imgur.com/y6h3i.png
This is a challenge that comes as part of a tutorial on Arrays, so I think that the aim is to use an array. My thinking is to convert the user's input into an array, iterate over each number and print the corresponding number of dashes for each number. I can't work out how to do this however. Any advice would be appreciated.
Thanks :)
| 0debug
|
static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid)
{
MXFDescriptor *descriptor = arg;
switch(tag) {
case 0x3F01:
descriptor->sub_descriptors_count = avio_rb32(pb);
if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))
return -1;
descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));
if (!descriptor->sub_descriptors_refs)
return -1;
avio_skip(pb, 4);
avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));
break;
case 0x3004:
avio_read(pb, descriptor->essence_container_ul, 16);
break;
case 0x3006:
descriptor->linked_track_id = avio_rb32(pb);
break;
case 0x3201:
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3203:
descriptor->width = avio_rb32(pb);
break;
case 0x3202:
descriptor->height = avio_rb32(pb);
break;
case 0x320E:
descriptor->aspect_ratio.num = avio_rb32(pb);
descriptor->aspect_ratio.den = avio_rb32(pb);
break;
case 0x3D03:
descriptor->sample_rate.num = avio_rb32(pb);
descriptor->sample_rate.den = avio_rb32(pb);
break;
case 0x3D06:
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3D07:
descriptor->channels = avio_rb32(pb);
break;
case 0x3D01:
descriptor->bits_per_sample = avio_rb32(pb);
break;
case 0x3401:
mxf_read_pixel_layout(pb, descriptor);
break;
default:
if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
if (!descriptor->extradata)
return -1;
descriptor->extradata_size = size;
avio_read(pb, descriptor->extradata, size);
}
break;
}
return 0;
}
| 1threat
|
systrace: Invalid trace result format for HTML output : <p>When I run
<strong>python systrace.py --time=10 -o mynewtrace.html gfx</strong> <br/>
The following error occurs<br></p>
<pre><code>Starting tracing (10 seconds)
Tracing completed. Collecting output...
<br>
</code></pre>
<blockquote>
<p><strong>Exception in thread Thread-11:</strong></p>
</blockquote>
<pre><code>Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()<br>
File "C:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, self.__kwargs)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\tracing_agents\atrace_agent.py", line 194, in _collect_a
nd_preprocess
self._trace_data = self._preprocess_trace_data(trace_data)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\tracing_agents\atrace_agent.py", line 272, in _preproces
s_trace_data
trace_data = strip_and_decompress_trace(trace_data)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\tracing_agents\atrace_agent.py", line 332, in strip_and_
decompress_trace
**trace_data = zlib.decompress(trace_data)**
</code></pre>
<blockquote>
<p><strong>error: Error -5 while decompressing data: incomplete or truncated stream</strong></p>
</blockquote>
<pre><code>Outputting Systrace results...<br>
Tracing complete, writing results<br>
Traceback (most recent call last):,br>
File "systrace.py", line 49, in <module>
sys.exit(run_systrace.main())<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\run_systrace.py", line 196, in main
main_impl(sys.argv)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\run_systrace.py", line 193, in main_impl
controller.OutputSystraceResults(write_json=options.write_json)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\systrace_runner.py", line 68, in OutputSystraceResults
self._out_filename)<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\output_generator.py", line 98, in GenerateHTMLOutput
html_file.write(_ConvertToHtmlString(result.raw_data))<br>
File "C:\Users\rajnish.r\AppData\Local\Android\Sdk\platform-tools\systrace\cat
apult\systrace\systrace\output_generator.py", line 120, in _ConvertToHtmlString
raise ValueError('Invalid trace result format for HTML output')<br>
*
</code></pre>
<blockquote>
<p><strong>ValueError: Invalid trace result format for HTML output</strong></p>
</blockquote>
<p>*</p>
| 0debug
|
static inline bool fp_access_check(DisasContext *s)
{
assert(!s->fp_access_checked);
s->fp_access_checked = true;
if (s->cpacr_fpen) {
return true;
}
gen_exception_insn(s, 4, EXCP_UDEF, syn_fp_access_trap(1, 0xe, false),
default_exception_el(s));
return false;
}
| 1threat
|
Best data-binding practice in Combine + SwiftUI? : <p>In RxSwift it's pretty easy to bind a <code>Driver</code> or an <code>Observable</code> in a <code>View Model</code> to some observer in a <code>ViewController</code> (i.e. a <code>UILabel</code>).</p>
<p>I usually prefer to build a pipeline, with observables <strong>created from other observables</strong>, instead of "imperatively" pushing values, say via a <code>PublishSubject</code>).</p>
<p>Let's use this example: <strong>update a <code>UILabel</code> after fetching some data from the network</strong></p>
<hr>
<h2>RxSwift + RxCocoa example</h2>
<pre class="lang-swift prettyprint-override"><code>final class RxViewModel {
private var dataObservable: Observable<Data>
let stringDriver: Driver<String>
init() {
let request = URLRequest(url: URL(string:"https://www.google.com")!)
self.dataObservable = URLSession.shared
.rx.data(request: request).asObservable()
self.stringDriver = dataObservable
.asDriver(onErrorJustReturn: Data())
.map { _ in return "Network data received!" }
}
}
</code></pre>
<pre class="lang-swift prettyprint-override"><code>final class RxViewController: UIViewController {
private let disposeBag = DisposeBag()
let rxViewModel = RxViewModel()
@IBOutlet weak var rxLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
rxViewModel.stringDriver.drive(rxLabel.rx.text).disposed(by: disposeBag)
}
}
</code></pre>
<hr>
<h2>Combine + UIKit example</h2>
<p>In a UIKit-based project it seems like you can keep the same pattern:</p>
<ul>
<li>view model exposes publishers</li>
<li>view controller binds its UI elements to those publishers</li>
</ul>
<pre class="lang-swift prettyprint-override"><code>final class CombineViewModel: ObservableObject {
private var dataPublisher: AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>
var stringPublisher: AnyPublisher<String, Never>
init() {
self.dataPublisher = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.google.it")!)
.eraseToAnyPublisher()
self.stringPublisher = dataPublisher
.map { (_, _) in return "Network data received!" }
.replaceError(with: "Oh no, error!")
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
</code></pre>
<pre class="lang-swift prettyprint-override"><code>final class CombineViewController: UIViewController {
private var cancellableBag = Set<AnyCancellable>()
let combineViewModel = CombineViewModel()
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
combineViewModel.stringPublisher
.flatMap { Just($0) }
.assign(to: \.text, on: self.label)
.store(in: &cancellableBag)
}
}
</code></pre>
<hr>
<h2>What about SwiftUI?</h2>
<p>SwiftUI relies on property wrappers like <code>@Published</code> and protocols like <code>ObservableObject</code>, <code>ObservedObject</code> to automagically take care of bindings (As of <em>Xcode 11b7</em>).</p>
<p>Since (AFAIK) property wrappers cannot be "created on the fly", there's no way you can re-create the example above using to the same pattern.
The following <strong>does not compile</strong></p>
<pre class="lang-swift prettyprint-override"><code>final class WrongViewModel: ObservableObject {
private var dataPublisher: AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>
@Published var stringValue: String
init() {
self.dataPublisher = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.google.it")!)
.eraseToAnyPublisher()
self.stringValue = dataPublisher.map { ... }. ??? <--- WRONG!
}
}
</code></pre>
<p>The closest I could come up with is <strong>subscribing in your view model (UGH!)</strong> and <strong>imperatively update your property</strong>, which does not feel right and reactive at all.</p>
<pre class="lang-swift prettyprint-override"><code>final class SwiftUIViewModel: ObservableObject {
private var cancellableBag = Set<AnyCancellable>()
private var dataPublisher: AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>
@Published var stringValue: String = ""
init() {
self.dataPublisher = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.google.it")!)
.eraseToAnyPublisher()
dataPublisher
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {_ in }) { (_, _) in
self.stringValue = "Network data received!"
}.store(in: &cancellableBag)
}
}
</code></pre>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
@ObservedObject var viewModel = SwiftUIViewModel()
var body: some View {
Text(viewModel.stringValue)
}
}
</code></pre>
<p>Is the "old way of doing bindings" to be forgotten and replaced, in this new <strong>UIViewController-less</strong> world?</p>
| 0debug
|
quickest way to swap index with values : <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>s = pd.Series(list('abcdefghij'), list('ABCDEFGHIJ'))
s
A a
B b
C c
D d
E e
F f
G g
H h
I i
J j
dtype: object
</code></pre>
<p>What is the quickest way to swap index and values and get the following</p>
<pre><code>a A
b B
c C
d D
e E
f F
g G
h H
i I
j J
dtype: object
</code></pre>
| 0debug
|
Please rate your Swift MVVM implementation : <p>I would like to be evaluated to ensure that Swift MVVM is implemented correctly.</p>
<p>Also, if there is anything else that can be supplemented, please modify it.</p>
<h1>1. AppDelegate.swift</h1>
<p>Before the ViewController is displayed, AppDelegate specifies a ViewModel.</p>
<pre><code> func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let rootVC = window?.rootViewController as? ViewController {
rootVC.viewModel = MainViewModel()
}
return true
}
</code></pre>
<h1>2. ViewController.swift</h1>
<p>Perform DataBinding in the ViewController.
TableView is also specified using extension.</p>
<pre><code>class ViewController: UIViewController {
var viewModel: MainViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel.bind { [weak self] in
DispatchQueue.main.async {
print("TableView reloadData")
// tableView reload
}
}
viewModel.addText(addText: "test")
print("count \(viewModel.count)")
}
}
class TextListCell: UITableViewCell {
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TextListCell = tableView.dequeueReusableCell(withIdentifier: "TextListCell", for: indexPath) as! TextListCell
let test = viewModel.texts[indexPath.row]
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row.description)")
}
}
</code></pre>
<h1>3. MainModel.swift</h1>
<p>Model is known as Data Management.
However, I don't understand that the Business Logic is being handled by a model.</p>
<pre><code>struct TextEditor {
let text: String
}
</code></pre>
<h1>4. MainViewModel.swift</h1>
<p>After the model update, inform the ViewModel of the results and prepare the data to be displayed in View.</p>
<pre><code>protocol MainViewModelProtocol: class {
func bind(didChange: @escaping () -> Void)
func addText(addText: String)
var count: Int { get }
var texts: Array<TextEditor> { get }
}
class MainViewModel: MainViewModelProtocol {
private var didChange: (() -> Void)?
var texts: [TextEditor] = [] {
didSet {
didChange?()
}
}
func bind(didChange: @escaping () -> Void) {
self.didChange = didChange
}
var count: Int {
return texts.count
}
func addText(addText: String) {
self.texts.append(TextEditor(text: addText))
}
}
</code></pre>
| 0debug
|
Initializing multiple variables in one line C++ : #include <iostream>
using namespace std;
int main() {
cout << "input a single letter";
int var;
cin >> var;
int vowel = 'a','e','i','o','u';
int consonant = 'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'
if (var == vowel) {
cout << "vowel";
} else if (var == consonant) {
cout << "consonant";
} else if (var != vowel && var != consonant) {
cout << "Error";
}
return 0;
}
this is my code for a program that prompts the user to provide a single letter, and it returns to you if the letter you inputted is a vowel or consonant. I am very very new at C++ and trying to learn why I'm coming back with an error message
| 0debug
|
Differences between 2 pointers of a template : <p>I want to know if there is any difference between 2 pointers (as data members) in a template class. For example:</p>
<pre><code>template <typename E>
class Link
{
private:
E element;
Link* a;
Link<E>* b;
};
</code></pre>
<p>Is "a" analogous to "b", I wonder?</p>
| 0debug
|
static void dbdma_cmdptr_load(DBDMA_channel *ch)
{
DBDMA_DPRINTF("dbdma_cmdptr_load 0x%08x\n",
be32_to_cpu(ch->regs[DBDMA_CMDPTR_LO]));
cpu_physical_memory_read(be32_to_cpu(ch->regs[DBDMA_CMDPTR_LO]),
(uint8_t*)&ch->current, sizeof(dbdma_cmd));
}
| 1threat
|
Is there any convenience way to get JSON element without type assertion? : I am mainly a python programmer and new Golang.
There are some inconvenience while processing JSON response from a web server.
For example, I don't know the data structure (and don't want to model it) of the JSON in advanced, and just want to get the value from it!
So, for Python, I can just write
value = response["body"][4]["data"]["uid"] //response is a dictionary
But for Golang, I need to do the assertion for every element!
value := response["body"].([]interface{})[4].(map[string]interface{})["data"].(map[string]interface{})["uid"]
//response is a map[string]interface{}
This is what I write in golang to get the value I need. Do you have any suggestion on it? It there any useful tips for this kind of case? Thank you.
| 0debug
|
How to open the device selector every time i run the app in Android Studio? : <p>I have a real device and an emulator. When i first install the app , the IDE asks me to select between the two but on subsequent runs it does not ask me to choose. How do i get it to ask me every time? I tried clicking on stop app , but the problem persists.</p>
| 0debug
|
ValueError: Unknown projection '3d' (once again) : <p><strong>Context:</strong> using Spyder version 3.3.4</p>
<p>When executing this line of code:</p>
<pre><code>import matplotlib.pyplot as plt
#your code
fig = plt.figure()
ax = fig.gca(projection='3d')
</code></pre>
<p>I have an output error:</p>
<pre><code>raise ValueError("Unknown projection %r" % projection)
ValueError: Unknown projection '3d'
<Figure size 432x288 with 0 Axes>
</code></pre>
<p>The same program is running on an old laptop where </p>
<pre><code>print('matplotlib: {}'.format(matplotlib.__version__))
</code></pre>
<p>While on a new machine:</p>
<pre><code>print('matplotlib: {}'.format(matplotlib.__version__))
matplotlib: 1.5.0rc3
</code></pre>
<p>A similar error was reported in <a href="https://stackoverflow.com/questions/3810865/matplotlib-unknown-projection-3d-error">this question (Stackoverflow)</a> but the answers do not help. Some suggestion on how to modify the instruction?
matplotlib: 3.0.2</p>
| 0debug
|
Why is the finally statement needed if there is no catch block? (Java) : My teacher was explaining how the `finally` statement is optional in a `try-catch` blockbut why is it absolutely necessary if there is no `catch` statement?
For example:
try{
for(int j = 0; j <= i.length; j++)
{
System.out.println(i[j]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Catch");
}//no errors
try{
for(int j = 0; j <= i.length; j++)
{
System.out.println(i[j]);
}
}//syntax error
Error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "Finally" to complete TryStatement
at Driver.main(Driver.java:12)
| 0debug
|
Easiest way to update TextView or String from AsyncTask : <p>It know this is possible in multiple ways like with bundles, params... But what is the shortest easiest way to update a textview or string data from an AsyncTask's OnPostExecute method?</p>
| 0debug
|
How to keep a scrollbar always bottom? : <p>I have a scroll-bar in a div element and initially it's position is top. Whenever i add some text to the div element then the scroll-bar does not move. Is there any way, the scroll-bar of the div element's position will be always bottom and whenever I add some text to the div element, the scroll-bar also goes to the bottom automatically?</p>
<p>Here's my div element: </p>
<pre><code><div class='panel-Body scroll' id='messageBody'></div>
</code></pre>
<p>And CSS class</p>
<pre><code>.scroll {
height: 450px;
overflow: scroll;
}
</code></pre>
<p>What i need is, initially the position of the scroll-bar should be bottom.</p>
<p>Also when i clicked a send message, I'm adding the message to the div elements 'messageBody'. On that time the the scroll-bar should be down again.</p>
<p>This is the current style of my scroll-bar
<a href="https://i.stack.imgur.com/OYcQ6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OYcQ6.png" alt="enter image description here"></a></p>
<p>And I want it to be always
<a href="https://i.stack.imgur.com/7zw1c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7zw1c.png" alt="enter image description here"></a></p>
<p>Thanks in advance.</p>
| 0debug
|
I cant use two OnClickListeners? : I have been trying to use two OnClickListeners but I cant figure out how to do it right.
Could anyone help me fix my code?
btnClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
numBase.getText().clear();
numNikotin.getText().clear();
}
btnAdd.setOnClickListener(new View.OnClickListener() { // I basically want this onClick Listener for the btnClear aswell, but I just cant get both to work. If I take away the btnClear setOnCLickListener Event then btnAdd works just fine.
public void onClick(View v) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
}
});
}
}
| 0debug
|
Google Cloud Datastore: Full text search? : <p>I am developing a database app using Google Cloud Datastore but don't see any built-in way of doing full-text search on fields. Is there a google-cloud-native solution?</p>
<p>The alternative I see is either:</p>
<ol>
<li><p>Do full text search application side (read in each row, find matches)</p></li>
<li><p>dupe the fields that need to be full-text-indexed into some other product like Google Cloud Sql (mysql) and use it's full-text-search capabilities instead.</p></li>
</ol>
| 0debug
|
new to ruby and don't understand yield : I come from a C#, java background and i don't know much about ruby. I have been piggy backing off my cousin's college course and all the work they get is fairly simple for me. I just got this one "while not being in that class and not having notes" looks like giberish to me.
mine=15
puts "Mine = 15"
def call_block
yield
yield
puts 'Now for some magic!'
end
call_block {mine}
print "Mine now is "
puts mine
the output is supposed to say
mine = 15
now for some Magic!
mine now is 25
This is a fix the problem to get the right output question.
I don't know anything about yield but from what I see I just add 10 to mine at some point no?
thanks for your help and explanations!
| 0debug
|
Add from one array to another by click. Angularjs2 : I have a json like:
"data":
[{
"max":10,
"class":"selected"
"type":"numbers"
}]
I want to use an angular *NgIf or other loop, which will start from 1 and to 10 (my max value) and display all the numbers inside span like:
<span>1</span><span>2</span>...<span>10</span>
Than if I click on the span element i want this element to be added in a new empty array. So lets say I have other empty array:
newarray: Array<number> = []
Will become:
newarray = [1]
Additionally I want to toggle class when you click on the span element, taken by the json.class property.
| 0debug
|
Is there a difference between malloc() and creating a variable and then using the & operator? : <p>In C, is there a difference between</p>
<pre><code>struct Foo foo;
struct Foo* fooPtr = &foo;
</code></pre>
<p>and</p>
<pre><code>struct Foo* fooPtr = (struct Foo*) malloc(sizeof(struct Foo));
</code></pre>
| 0debug
|
Dicom files in object detection problems : <p>I have faced with an issue of working with dicom files in object detection. I need to recognize various objects on the CT (computer tomography) images.</p>
<p>I tried to follow this tutorial. The author uses jpeg files for labeling the dataset, obtaining a csv file with the coordinates of objects on the images:</p>
<p><a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10</a></p>
<p>I need to do almost the same except the fact that I do not have jpegs, instead I have a big number of dicom files. I tried to convert them into jpegs, however there was a quality loss in the resulting files.</p>
<p>My questions are:</p>
<p>1) is there any good way of converting dicom files into jpegs without big quality loss?</p>
<p>2) is there any other approach for object detection on dicom files?</p>
<p>Thanks in advance!</p>
| 0debug
|
pip install netmiko error : Installing collected packages: setuptools, idna, ipaddress, enum34, cryptography, paramiko, scp, pyyaml, netmiko
Found existing installation: setuptools 1.1.6
Uninstalling setuptools-1.1.6:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_set.py", line 736, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_install.py", line 742, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/utils/__init__.py", line 267, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 299, in move
copytree(src, real_dst, symlinks=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 208, in copytree
raise Error, errors
Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py', '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py', "[Errno 1] Operation not permitted: '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc', '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc', "[Errno 1] Operation not permitted: '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py', '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py', "[Errno 1] Operation not permitted: '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc', '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc', "[Errno 1] Operation not permitted: '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib', '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib', "[Errno 1] Operation not permitted: '/var/folders/8g/tm8510z944sfdk9pkzp1wd2c0000gn/T/pip-XZiudu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib'")]
| 0debug
|
Ealuate jQuery code nested in the object when object is used : I have a JS object like:
{
'element1':{'redirectURI' : 'abc.php?toDate='+encodeURIComponent(jQuery('.dateField1').val())},
'element2':{'redirectURI' : 'pqr.php?&toDate='+encodeURIComponent(jQuery('.dateField2').val())}
};
I need the **redirectURI** index to be evaluated when the object is used i.e. when `obj['element1']['redirectURI']` or `obj['element2']['redirectURI']`.
How to achieve this?
Right now `jQuery('.dateField2').val()` takes the value available when this object is parsed,the date field is a datepicker whose value can vary.
Thanks.
| 0debug
|
static void vnc_listen_read(void *opaque)
{
VncDisplay *vs = opaque;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
vga_hw_update();
int csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
if (csock != -1) {
vnc_connect(vs, csock);
}
}
| 1threat
|
fill array with random but unique numbers in C# : <p>Okay I know there are few posts like this but I need to use only loops (for,do,while) and if, else to fill array with random but unique numbers so how shall i edit this code</p>
<pre><code> int[] x = new int[10];
Random r = new Random();
int i;
for (i = 0; i < x.Length; i++) {
x[i] = r.Next(10);
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
</code></pre>
| 0debug
|
static void rm_read_metadata(AVFormatContext *s, int wide)
{
char buf[1024];
int i;
for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
int len = wide ? avio_rb16(s->pb) : avio_r8(s->pb);
get_strl(s->pb, buf, sizeof(buf), len);
av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0);
}
}
| 1threat
|
TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *old_op,
TCGOpcode opc, int nargs)
{
int oi = s->gen_next_op_idx;
int prev = old_op->prev;
int next = old_op - s->gen_op_buf;
TCGOp *new_op;
tcg_debug_assert(oi < OPC_BUF_SIZE);
s->gen_next_op_idx = oi + 1;
new_op = &s->gen_op_buf[oi];
*new_op = (TCGOp){
.opc = opc,
.prev = prev,
.next = next
};
s->gen_op_buf[prev].next = oi;
old_op->prev = oi;
return new_op;
}
| 1threat
|
Unable to use sed to replace text with shell variable : <p>For some reason, the answer in the post below doesn't work for me. Any thoughts?<br>
<a href="https://stackoverflow.com/questions/15230020/how-to-use-sed-to-replace-a-string-in-a-file-with-a-shell-variable">how to use sed to replace a string in a file with a shell variable</a> </p>
<p>I'm running CentOS 6.5</p>
<pre><code>`NEW="new value"
cat myfile.txt | sed -e 's/old/${NEW}' <-- just replaces 'old' with '${NEW}'
cat myfile.txt | sed -e 's/old/$NEW' <-- just replaces 'old' with '$NEW'
cat myfile.txt | sed -e "s/old/${NEW}" <-- gives the error: unknown option to `s'
</code></pre>
| 0debug
|
how to edit strings in a list (PYTHON) : i am not so familiar with python, and i don't know how to do this.. So I have a list that looks like this:
animal_id = ['id01', 'id02', 'id03', 'id04', 'id05']
and I would like to make a new list from the list above, using string manipulation. and the new list should look like this:
animal_list = ['a01', 'a02', 'a03', 'a04', 'a05']
i think i would have to make a for loop, but i dont know what methods (in string) to use to achieve the desired output
| 0debug
|
void visit_type_uint32(Visitor *v, uint32_t *obj, const char *name, Error **errp)
{
int64_t value;
if (v->type_uint32) {
v->type_uint32(v, obj, name, errp);
} else {
value = *obj;
v->type_int64(v, &value, name, errp);
if (value < 0 || value > UINT32_MAX) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
name ? name : "null", "uint32_t");
return;
}
*obj = value;
}
}
| 1threat
|
SQL - Procedure & Query with SUM & return - Need help - Willing pay 15$ : I'am trying to do a **Procedure** with a sub query who do a **SUM**.
The procedure should list all items of <ProductFinished> (I.e Pizza etc) and list the ingredients , with unit price of ingredient and the total sum of cost of the finished product.
UML of the Database :
http://i.stack.imgur.com/B7r8R.png
**I'am willing to pay 15$ Paypal for anyone who help me figure it out/do this query.**
The product <NameFInishedProduct> is composed of
3 <NameRawProduct> priced <BuyPrice> € each
1 <NameRawProduct> priced <BuyPrice> € each
The total price of the <NameFInishedProduct> is <SUM> €.
Witch in normal output should look like
The product Pizza is composed of
3 Tomato priced 2 € each
1 Cheese priced 1€ each
The total price of the Pizza is 7 €.
| 0debug
|
Why cant I get a reference to a value in a map? : <p>I am quite confused about everything being a reference in most cases but sometimes not, and containers. Consider this piece of code:</p>
<pre><code>HashMap<Integer,String> x_map = new HashMap<>();
x_map.put(42,"foo");
String g = x_map.get(42);
g = "bar";
System.out.println(g.equalsIgnoreCase(x_map.get(42)));
</code></pre>
<p>Why does this print <code>false</code> ?</p>
<p>I found the correct way to do it:
<a href="https://stackoverflow.com/questions/4157972/how-to-update-a-value-given-a-key-in-a-java-hashmap?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa">How to update a value, given a key in a java hashmap?</a>, but I am totaly lost why the above does not work as expected. Also when the objects in the map are rather large then I would like to be able to modify only a single member of one of the values in the map and currently I dont know how to do that without creating a new instance and put that into the map.</p>
| 0debug
|
How to convert seconds to minutes and hours in javascript : <p>I have a count of seconds stored in variable <code>seconds</code>. I want to convert for example 1439 seconds to 23 minutes and 59 seconds. And if the time is greater than 1 hour (for example 9432 seconds), to 2 hours, 37 minutes and 12 seconds.</p>
<p>How can I achieve this?</p>
<p>I'm thinking of:</p>
<pre><code>var sec, min, hour;
if(seconds<3600){
var a = Math.floor(seconds/60); //minutes
var b = seconds%60; //seconds
if (b!=1){
sec = "seconds";
}else{
sec = "second";
}
if(a!=1){
min = "minutes";
}else{
min = "minute";
}
$('span').text("You have played "+a+" "+min+" and "+b+" "+sec+".");
}else{
var a = Math.floor(seconds/3600); //hours
var x = seconds%3600;
var b = Math.floor(x/60); //minutes
var c = seconds%60; //seconds
if (c!=1){
sec = "seconds";
}else{
sec = "second";
}
if(b!=1){
min = "minutes";
}else{
min = "minute";
}
if(c!=1){
hour = "hours";
}else{
hour = "hour";
}
$('span').text("You have played "+a+" "+hour+", "+b+" "+min+" and "+c+" "+sec+".");
}
</code></pre>
<p>But that's a lot of code, and it has to be calculated each second. How can I shrink this up?</p>
| 0debug
|
Angular 2 Material tooltip with HTML content in angular : <p>I am trying to bind the HTML strings into angular 2 tool tip. But it's rendering as HTML it showing as a plain string. Is there any way to do render string as an HTML.</p>
<p>Here is my code:</p>
<p>In View:</p>
<pre><code> <span class="icon-status" mdTooltip="{{value.status}}"></span>
</code></pre>
<p>Component:</p>
<pre><code>value.status = this.sanitizer.bypassSecurityTrustHtml(this.getStatusTemplate(value.status));
getStatusTemplate(status: IIconStatus): string{
let HTML =`
<div>Event Title</div>
<div class="">
<table>
<thead>
<th>User</th>
<th>User</th>
<th>User</th>
<th>User</th>
</thead>
</table>
</div>
`;
return HTML;}
</code></pre>
<p>Thanks in advance.</p>
| 0debug
|
static int dca_convert_bitstream(uint8_t * src, int src_size, uint8_t * dst,
int max_size)
{
uint32_t mrk;
int i, tmp;
uint16_t *ssrc = (uint16_t *) src, *sdst = (uint16_t *) dst;
PutBitContext pb;
mrk = AV_RB32(src);
switch (mrk) {
case DCA_MARKER_RAW_BE:
memcpy(dst, src, FFMIN(src_size, max_size));
return FFMIN(src_size, max_size);
case DCA_MARKER_RAW_LE:
for (i = 0; i < (FFMIN(src_size, max_size) + 1) >> 1; i++)
*sdst++ = bswap_16(*ssrc++);
return FFMIN(src_size, max_size);
case DCA_MARKER_14B_BE:
case DCA_MARKER_14B_LE:
init_put_bits(&pb, dst, max_size);
for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
put_bits(&pb, 14, tmp);
}
flush_put_bits(&pb);
return (put_bits_count(&pb) + 7) >> 3;
default:
}
}
| 1threat
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.