problem
stringlengths
26
131k
labels
class label
2 classes
secant method in Python to solve f(x) = 0 : <p>How can I use the secant method in Python to solve the equation f(x) = 0 given 2 intial guesses, x0 and x1?.</p> <pre><code>def secant(f,x0,x1,tol): </code></pre> <p>I need to use it to find solutions to quadratics and higher factors of x, for example, x^3 -4x^2 + 1 = 0 for a given interval. This is just a shot in the dark so any links to useful websites will also be appreciated!</p>
0debug
How can I make a program to operate another program? : <p>So what I'm wanting to do is pretty lame. Anyway, what I'm wanting to do is basically make a bot that will do some specified tasks for me.</p> <p>I have an emulator on my laptop that when open, operates like an Android phone, and I'm using Snapchat on it. What I have been trying to do is make it send my 'streaks' on Snapchat a picture everyday at specified times. I have tried using a Macro Recorder to do this, but the loading time varies. </p> <p>My questions are:</p> <p>1) What programming language should I use for this?</p> <p>2) What would be the best application to use? (Like Notepad, or some other application)</p> <p>Any help is appreciated :)</p>
0debug
Using Webpack with React-router bundle.js Not Found : <p>I build a project with Webpack and react-rounter. this is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>ReactDOM.render( &lt;Provider store={store}&gt; &lt;Router history={ browserHistory }&gt; &lt;Route path='/' component={ App } &gt; &lt;IndexRoute component={ Home } /&gt; &lt;Route path="purchase" component={ Purchase } /&gt; &lt;Route path="purchase/:id" component={ Purchase } /&gt; &lt;/Route&gt; &lt;/Router&gt; &lt;/Provider&gt;, document.getElementById('example') );</code></pre> </div> </div> </p> <p>When i request <code>"http://127.0.0.1:3001/purchase"</code>, it's work! but the address <code>"http://127.0.0.1:3001/purchase/a"</code> has error. look the error message:<a href="http://i.stack.imgur.com/UJuJ4.png" rel="noreferrer">enter image description here</a></p> <p>My WebpackDevServer config is:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>new WebpackDevServer (webpack(config), { publicPath: config.output.publicPath, hot: true, noInfo: false, historyApiFallback: true }).listen(3001, '127.0.0.1', function (err, result) { if (err) { console.log(err); } console.log('Listening at localhost:3001'); });</code></pre> </div> </div> </p> <p>I don't know what the matter, Help me!</p>
0debug
static void setup_rt_frame(int sig, struct target_sigaction *ka, target_siginfo_t *info, target_sigset_t *set, CPUM68KState *env) { struct target_rt_sigframe *frame; abi_ulong frame_addr; abi_ulong retcode_addr; abi_ulong info_addr; abi_ulong uc_addr; int err = 0; int i; frame_addr = get_sigframe(ka, env, sizeof *frame); if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) goto give_sigsegv; __put_user(sig, &frame->sig); info_addr = frame_addr + offsetof(struct target_rt_sigframe, info); __put_user(info_addr, &frame->pinfo); uc_addr = frame_addr + offsetof(struct target_rt_sigframe, uc); __put_user(uc_addr, &frame->puc); err |= copy_siginfo_to_user(&frame->info, info); __put_user(0, &frame->uc.tuc_flags); __put_user(0, &frame->uc.tuc_link); __put_user(target_sigaltstack_used.ss_sp, &frame->uc.tuc_stack.ss_sp); __put_user(sas_ss_flags(env->aregs[7]), &frame->uc.tuc_stack.ss_flags); __put_user(target_sigaltstack_used.ss_size, &frame->uc.tuc_stack.ss_size); err |= target_rt_setup_ucontext(&frame->uc, env); if (err) goto give_sigsegv; for(i = 0; i < TARGET_NSIG_WORDS; i++) { if (__put_user(set->sig[i], &frame->uc.tuc_sigmask.sig[i])) goto give_sigsegv; } retcode_addr = frame_addr + offsetof(struct target_sigframe, retcode); __put_user(retcode_addr, &frame->pretcode); __put_user(0x70004600 + ((TARGET_NR_rt_sigreturn ^ 0xff) << 16), (long *)(frame->retcode + 0)); __put_user(0x4e40, (short *)(frame->retcode + 4)); if (err) goto give_sigsegv; env->aregs[7] = frame_addr; env->pc = ka->_sa_handler; unlock_user_struct(frame, frame_addr, 1); return; give_sigsegv: unlock_user_struct(frame, frame_addr, 1); force_sig(TARGET_SIGSEGV); }
1threat
static void flush_compressed_data(QEMUFile *f) { int idx, len, thread_count; if (!migrate_use_compression()) { return; } thread_count = migrate_compress_threads(); for (idx = 0; idx < thread_count; idx++) { if (!comp_param[idx].done) { qemu_mutex_lock(comp_done_lock); while (!comp_param[idx].done && !quit_comp_thread) { qemu_cond_wait(comp_done_cond, comp_done_lock); } qemu_mutex_unlock(comp_done_lock); } if (!quit_comp_thread) { len = qemu_put_qemu_file(f, comp_param[idx].file); bytes_transferred += len; } } }
1threat
Swift: Page ViewController with 4 viewController - how to set view 2 as initial viewController? : I have created a pageViewController with four view controller. Right now the order is: VC1, VC2, VC3, VC4: var pageControl = UIPageControl() var pendingPage: Int? lazy var viewControllerList: [UIViewController] = { let sb = UIStoryboard(name: "Main", bundle: nil) let vc1 = sb.instantiateViewController(withIdentifier: "VC1") let vc2 = sb.instantiateViewController(withIdentifier: "VC2") let vc3 = sb.instantiateViewController(withIdentifier: "VC3") let vc4 = sb.instantiateViewController(withIdentifier: "VC4") return [vc1, vc2, vc3, vc4] }() How can I set VC2 as the initial view controller of the page view controller when the app loads? So basically the user can swipe left "and" right to got to from VC2 left to VC1 or right from VC2 to VC3. VC1 < VC2 - this is the start view controller > VC3 > VC4 This is my viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() self.delegate = self self.dataSource = self if let firstViewController = viewControllerList.first { self.setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } }
0debug
hi, i have a page with side navbar, i want to move this side navbar when i change the page direction to rtl : I have a page which has one sidebar to open different pages. It is working as desired with direction left to right but I want to move this sidebar to the right side when i change the page direction to right to left. Following is the HTML of my page. I have searched on internet but I did not get any solution. From my side I have tried to change the direction of the page in HTML but it is not working.
0debug
Java/Android loop list only remembers last member : I have this list of users [{"id":1,"name":"Radovan","username":"1","password":"1","photo":"slika"}, {"id":2,"name":"Milovan","username":"2","password":"2","photo":"slika"}, {"id":3,"name":"Zivan","username":"3","password":"3","photo":"slika"}] How do I go through whole list and remember every user in it, because when I go for(int i = 0; i < users.size(); i++), only last user is remembered.
0debug
Spring Boot: How to keep DDD entities clean from JPA/Hibernate Annotations? : <p>I am writing an application that I wish to follow the DDD patterns, a typical entity class looks like this:</p> <pre><code>@Entity @Table(name = "mydomain_persons") class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name="fullname") private String fullName; @OneToMany(cascade=ALL, mappedBy="item") private Set&lt;Item&gt; items; } </code></pre> <p>As you see, since the JPA/Hibernate heavily relies on annotations on entity classes, my domain entity classes are now polluted by persistence-aware annotations. This violates DDD principles, as well as separation of layers. Also it gives me problems with properties unrelated to ORM, such as events. If I use @Transient, it will not initialize a List of events and I have to do this manually or get weird errors. </p> <p>Id like the domain entity to be a POJO(or POKO as I use Kotlin), so I do not want to have such annotations on the entity class. However I definitely do not wish to use XML configurations, its a horror and the reason why Spring developers moved on to annotations in the first place. </p> <p>What are the options I have available? Should I define a DTO class that contains such annotations and a Mapper class that converts each DTO into the corresponding Domain Entity? Is this a good practice? </p> <p>Edit: I know in C# the Entity Framework allows creation of mapping classes outside of Entity classes with Configuration classes, which is a way better alternative than XML hell. I aint sure such technique is available in the JVM world or not, anyone knows the below code can be done with Spring or not? </p> <pre><code>public class PersonDbContext: DbContext { public DbSet&lt;Person&gt; People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Write Fluent API configurations here //Property Configurations modelBuilder.Entity&lt;Person&gt;().Property(p =&gt; p.id).HasColumnName("id").IsRequired(); modelBuilder.Entity&lt;Person&gt;().Property(p =&gt; p.name).hasColumnName("fullname").IsRequired(); modelBuilder.Entity&lt;Person&gt;().HasMany&lt;Item&gt;(p =&gt; p.items).WithOne(i =&gt; i.owner).HasForeignKey(i =&gt; i.ownerid) } </code></pre>
0debug
Sorting by Rank in R : <p>I need help creating a way of sorting a column in R so that I can plot household rank by consumption per capita. I have a column with all of the consumption per capita which will go on the y-axis and then need to put their "rank" on the x-axis from [0,1] separated by .1. I have 4200 consumption per capita data points so everyone from [1,420] should go in the first .1 percentile and so on. </p>
0debug
How do I make my function as asynchronous in Javascript? : <p>I am trying to understand the async behaviour of Javascript, how can we implement in normal functions. For example below code I am trying to implement a custom SetTimeout function which would work asynchronously. It should call the function <code>muCsutSetInterval</code> and go the <code>console.log("after");</code>. </p> <p>Please suggest the right way to do it. Appreciate your help..</p> <pre><code>var myCustSetInterval = function (time, callback){ let initial = new Date(); let current; while(true){ current = new Date(); if(current.getTime()-initial.getTime()===time){ break; } } callback(); } console.log("before"); myCustSetInterval(5000,()=&gt;{ console.log("Callback"); }); console.log("after"); </code></pre>
0debug
using cuda atomicAdd to port this peice of code : this is my sequential code: float foo(float* in1, float* in2, float in3, unsigned int size) { float tmp = 0.f; for (int i = 0; i<size; i++) if(in2[i]>0)tmp += (in1[i]/in3 - (in2[i] /in3)*(in2[i] /in3)); return tmp; } this is my effort for port it to cuda: __global__ void kernel_foo(float* tmp, const float* in1, const float* in2, float in3, unsigned int size) { unsigned int i = blockDim.x * blockIdx.x + threadIdx.x; if (i < size) { if(in2[i]>0){ atomicAdd(tmp, in1[i]/in3 - (in2[i] /in3)*(in2[i] /in3)); } } } void launch_kernel_foo(float* tmp, const float* in1, const float* in2, float in3, unsigned int size) { kernel_foo<<<(size+255)/256,256>>>(tmp, in1, in2, in3, size); } but it does't work, could anyone tell me where is wrong? thank you
0debug
Custom describe or aggregate without groupby : <p>I want to use <code>groupby.agg</code> where my group is the entire dataframe. Put another way, I want to use the <code>agg</code> functionality, without the groupby. I've looked for an example of this, but can not find it.</p> <p>Here's what I've done:</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) df = pd.DataFrame(np.random.rand(6, 4), columns=list('ABCD')) df </code></pre> <p><a href="https://i.stack.imgur.com/GLb3X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GLb3X.png" alt="df"></a></p> <pre><code>def describe(df): funcs = dict(Kurt=lambda x: x.kurt(), Skew='skew', Mean='mean', Std='std') one_group = [True for _ in df.index] funcs_for_all = {k: funcs for k in df.columns} return df.groupby(one_group).agg(funcs_for_all).iloc[0].unstack().T describe(df) </code></pre> <p><a href="https://i.stack.imgur.com/jC65x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jC65x.png" alt="enter image description here"></a></p> <h3>Question</h3> <p>How was I supposed to have done this?</p>
0debug
Please help me with the Installation KnpSnappyBundle Symfony 2.8 : i just need to install a bundle which help me to generate pdf's files, but, i dont know how to start to install, i dont understand the documentation, the KnpSnappyBundle's documentation says to install with composer to make: { "require": { "knplabs/knp-snappy-bundle": "~1.4" } } but i dont know where put such code. Nevertheless I am open to other bundle in which i can create pdfs files, and please explain me STEP BY STEP how to install it, i am a beginner in symfony. since now thank you very very very much
0debug
replace javascript function with a new function : <p>In our ordering system there is an embedded function I have no access to at all. Conveniently there is a spelling error in it so when a user clicks something a popup appears and has grammar issues in it.</p> <p>Is there a way for me to replace that text or replace the function with a new function that has all the same code but correct spelling?</p> <p>This is the function I need to edit.. note confirm says 'You selection' not 'Your selection' I'd prefer to replace the whole thing because I may want to do some other edits but for now I'd like to fix that spelling error.</p> <pre><code> function showProof() { var blnSubmit = false; var strHid=''; var strSave=''; if (aryTemplateChoices.length == 0) { blnSubmit = true; } else { for (var i=1; i&lt;=aryTemplateChoices.length; i++) { strSave = aryTemplateChoices[i-1]; if (strSave=='')strSave='0'; if (document.getElementById('hidctrl'+ i))strHid = document.getElementById('hidctrl'+ i).value; if (strHid=='')strHid='0'; if ((strSave != '0') &amp;&amp; (strHid != strSave)) { blnSubmit = true; break; } } } if (blnSubmit) { if (confirm('Your selection has changed, do you want to save?')) { document.getElementById('subtype').value = 'proof'; document.getElementById('prevclick').value = ''; document.getElementById('frm1').submit(); } } canAddToCart(); //&lt;!--WRITE--&gt; getQuantityPrice() //&lt;!--/WRITE--&gt; loadProof(); } </code></pre>
0debug
Which one is more efficient in terms of boolean in java? : <p>Which one is more efficient in terms of boolean in java ?</p> <pre><code>Boolean boolean; if(boolean == false) {} </code></pre> <p>OR</p> <pre><code>if(!boolean) {} </code></pre>
0debug
Below is the code i write to get the html str of my result. Need to Bold the html header : def gen_table(Header,Tuple,HeaderColor='#c8f98e',WeekendColor='#e9fcd0',Weekendflag=1,bcolor=[],opt="center"): html_str='' found_list = [] color1 = "white" if Tuple: if Header: html_str+='\n<table border=1>\n' if type(Header)==list: html_str+='<tr bgcolor="'+str(HeaderColor)+'">\n' for value in Header: html_str+='<th align="'+opt+'">'+str(value)+'</th>\n' html_str+='</tr>\n' else: for value in Header: html_str+='<tr bgcolor="'+str(HeaderColor)+'" align="'+opt+'">\n' for col in value: html_str+=tbody(col,b='True') html_str+='</tr>\n' dic = find(Tuple) for rows in Tuple: if Weekendflag: if type(rows[0])==datetime.date and rows[0].weekday() in (6,5,) : html_str+="<tr bgcolor='"+str(WeekendColor)+"' align='"+opt+"'>\n" else: html_str+='\n<tr bgcolor="'+str(color1)+'" align="'+opt+'">\n' else: html_str+='\n<tr bgcolor="'+str(color1)+'" align="'+opt+'">\n' for i in range(len(rows)): if len(rows)<=1: html_str+="<b><td colspan=11 rowspan=1 bgcolor='"+str(WeekendColor)+"'>%s</td></b>\n"%rows[i] elif dic.has_key(rows[i]) and rows[i] not in found_list: found_list.append(rows[i]) html_str+="<td colspan=1 rowspan=%s>%s</td>\n" %(dic[rows[i]],rows[i]) elif rows[i] not in found_list: html_str+=tbody(rows[i],HeaderColor,bcolor,i) html_str+='</tr>\n' html_str+='</table>' else: html_str+='---NO DATA---' Here i need to get the header alone in bold. I added <b> </b> in those part. But i cant.. Could anyone help me here.
0debug
If anyone can help it will be hugely appreciated! -- How can I create an empty 3d multidimensional array (PYTHON) : #This here code is my attempt at creating an empty 3d array. n=3 board = [[[ 0 for _ in range(n)] for _ in range(n)] for _ in range(n)] print(board) # so what that creates is exactly what im looking for a 3d array with dimensions n by n by n, but the list is filled with 0's and if i take out the 0 an error occurs. How i would i create this same list but empty?
0debug
What is the equivalent of 'head :ok' from Rails in Phoenix? : <p>I want to return a response that has no content (merely headers) like <a href="http://apidock.com/rails/ActionController/Head/head" rel="noreferrer">this one</a></p> <pre><code>def show head :ok end </code></pre>
0debug
If Loop Not working Correctly Won't Pass If Statement : I'm making a magic 8 ball within the cmd. I want to ask the user if they would like to do. I want the program to keep asking questions until the user selects the letter E. If they try to shake before they ask a question then they will get an error. The issue that I'm having is that when you enter A, you will enter a question. Then when I enter S right after, I get the error message searching RAM and it doesn't call my shake method. public static string userAnswer = ""; static void Main(string[] args) { Console.WriteLine("Main program!"); Console.WriteLine("Welcome to the Magic 8 Ball"); Console.WriteLine("What would you like to do?"); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball(); string input = Console.ReadLine().ToUpper(); do { if (input == "S") { if (userAnswer != null) { Console.WriteLine("Searching the Mystic Realms(RAM) for the answer"); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); input = Console.ReadLine(); } else { //Call Method Shake() ball.Shake(); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); input = Console.ReadLine(); } } else if (input == "A") { userAnswer = Console.ReadLine(); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); input = Console.ReadLine(); } else if (input == "G") { if (userAnswer != null) { Console.WriteLine("Please Enter A Question Before Asking For An Answer."); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); input = Console.ReadLine(); } else { //Call Method GetAnswer() ball.GetAnswer(); Console.WriteLine("(S)hake the Ball"); Console.WriteLine("(A)sk a Question"); Console.WriteLine("(G)et the Answer"); Console.WriteLine("(E)xit the Game"); input = Console.ReadLine(); } } }while (input != "E"); } } }
0debug
static void tcg_out_qemu_ld(TCGContext* s, TCGReg data_reg, TCGReg addr_reg, TCGMemOpIdx oi) { TCGMemOp opc = get_memop(oi); #ifdef CONFIG_SOFTMMU unsigned mem_index = get_mmuidx(oi); tcg_insn_unit *label_ptr; TCGReg base_reg; base_reg = tcg_out_tlb_read(s, addr_reg, opc, mem_index, 1); label_ptr = s->code_ptr + 1; tcg_out_insn(s, RI, BRC, S390_CC_NE, 0); tcg_out_qemu_ld_direct(s, opc, data_reg, base_reg, TCG_REG_R2, 0); add_qemu_ldst_label(s, 1, oi, data_reg, addr_reg, s->code_ptr, label_ptr); #else TCGReg index_reg; tcg_target_long disp; tcg_prepare_user_ldst(s, &addr_reg, &index_reg, &disp); tcg_out_qemu_ld_direct(s, opc, data_reg, addr_reg, index_reg, disp); #endif }
1threat
static void qxl_reset_state(PCIQXLDevice *d) { QXLRam *ram = d->ram; QXLRom *rom = d->rom; assert(SPICE_RING_IS_EMPTY(&ram->cmd_ring)); assert(SPICE_RING_IS_EMPTY(&ram->cursor_ring)); d->shadow_rom.update_id = cpu_to_le32(0); *rom = d->shadow_rom; qxl_rom_set_dirty(d); init_qxl_ram(d); d->num_free_res = 0; d->last_release = NULL; memset(&d->ssd.dirty, 0, sizeof(d->ssd.dirty)); }
1threat
What's the replacement of '++' and '--' in swift3? : <p>Since the expression '++' and '--' will be removed in Swift 3, the follow code will be invalid.</p> <pre><code> return i &lt; 0 ? nil : i-- </code></pre> <p>Now I just rewrite it like this</p> <pre><code>if i &lt; 0 { return nil } let res = i i -= 1 return res </code></pre> <p>But it looks too .... cumbersome.</p> <p>How to rewrite this code as short as possible in Swift 3?</p>
0debug
float32 helper_fsqrts(CPUSPARCState *env, float32 src) { float32 ret; clear_float_exceptions(env); ret = float32_sqrt(src, &env->fp_status); check_ieee_exceptions(env); return ret; }
1threat
how to fix an error on a simulation? : Please help me to find the errors .I am trying to run a simulation but I keep getting some kind of error.I am not very experienced in c++ .I will attach both files the main file of the simulation and the file ndn-v2v.. i will appreciate any help i can get even a small advice and thanks in advance.[i also added a screen capture for the error while compilling the script here][1] enter code here #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/mobility-module.h" #include "ns3/config-store-module.h" #include "ns3/wifi-module.h" #include "ns3/internet-module.h" #include "ns3/ndnSIM-module.h" #include "ns3/corner-propagation-loss-model.h" #include "ns3/ndn-v2v-net-device-face.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include "../src/ndnSIM/utils/tracers/ndn-l3-aggregate-tracer.h" #include "../src/ndnSIM/utils/tracers/ndn-l3-rate-tracer.h" #include "../src/ndnSIM/utils/tracers/v2v-tracer.h" NS_LOG_COMPONENT_DEFINE ("Wifiv2v"); using namespace ns3; #define MAX_NODES 1002; static int packet_count = 0; // Variable for simulation-traces //------------------------------------// //------------------------------------// //------------------------------------// int mac_tx_count = 0; // counts how many packets a rereceived from the higher layers in order to be enqueued for transmission int mac_tx_drop = 0; //counts how many packets are has been dropped in the Mac layer before beeing queued for transmission int mac_rx_count = 0; //counts how many packets a rereceived from the phy layer and is being forwarded to the local protocol stack int mac_rx_drop = 0; //counts how many packtes has been dropped in the Mac layer after has been passed //up from phylayer //------------------------------------// //------------------------------------// // Call back for simulation-traces //------------------------------------// //------------------------------------// void MacTxCount(Ptr<const Packet> p) { mac_tx_count++; NS_LOG_DEBUG( "[MACTXCOUNT] Packet is going to be transmitted...mac_tx_count=" << mac_tx_count); } void MacTxDrop(Ptr<const Packet> p) { mac_tx_drop++; NS_LOG_DEBUG( "[MAC_TX_DROP] Packet has been dropped before transmission...mac_tx_drop=" << mac_tx_drop); } void MacRxCount(Ptr<const Packet> p) { mac_rx_count++; NS_LOG_DEBUG( "[MAC_RX_COUNT] Packet has been received,going to forward...mac_rx_drop=" << mac_rx_count); } void MacRxDrop(Ptr<const Packet> p) { mac_rx_drop++; NS_LOG_DEBUG( "[MAC_RX_DROP] Packet has been dropped by Mac before forward...mac_rx_drop=" << mac_rx_drop); } void PrintTrasmission() { //std::cout<<Simulator::Now().GetSeconds()<<"\t"<< mac_tx_count << "\t" << mac_tx_drop << "\t" << mac_rx_count << "\t" << mac_rx_drop << "\n "; NS_LOG_DEBUG( " [ PRINT-TRANSMISSION]Time=" << Simulator::Now().GetSeconds() << " mac_tx_count=" << mac_tx_count << " mac_tx_drop= " << mac_tx_drop << " mac_rx_count= " << mac_rx_count << " mac_rx_drop=" << mac_rx_drop); Simulator::Schedule(Seconds(5.0), &PrintTrasmission); } void OutInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[OUT INTEREST]Time=" << Simulator::Now().GetSeconds() << " NID= " << face->GetNode()->GetId() << " Nonce= " << interestHeader->GetNonce() << "Name=" << interestHeader->GetName() << "\n"); } void InInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[IN INTEREST]Time=" << Simulator::Now().GetSeconds() << "NID=" << face->GetNode()->GetId() << "Nonce=" << interestHeader->GetNonce() << "Name=" << interestHeader->GetName() << "Position=" << face->GetNode()->GetObject<MobilityModel>()->GetPosition() << "\n"); } void DropInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[DROPINTEREST]Time=" << Simulator::Now().GetSeconds() << "NID=" << face->GetNode()->GetId() << "Nonce=" << interestHeader->GetNonce() << "Name=" << interestHeader->GetName() << "\n"); } void InData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader, Ptr<const ns3::Packet> packet, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[INDATA]Time=" << Simulator::Now().GetSeconds() << "NID=" << face->GetNode()->GetId() << "Name=" << contentHeader->GetName() << "Position=" << face->GetNode()->GetObject<MobilityModel>()->GetPosition() << "\n "); } void OutData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader, Ptr<const ns3::Packet> packet, bool value, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[OUT DATA]Time=" << Simulator::Now().GetSeconds() << "NID=" << face->GetNode()->GetId() << "Name=" << contentHeader->GetName() << "\n"); } void DropData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader, Ptr<const ns3::Packet> packet, Ptr<const ns3::ndn::Face> face) { NS_LOG_DEBUG( "[DROP DATA]Time=" << Simulator::Now().GetSeconds() << "NID=" << face->GetNode()->GetId() << "Name=" << contentHeader->GetName() << "\n"); } Ptr<ndn::NetDeviceFace> V2vNetDeviceFaceCallback(Ptr<Node> node, Ptr<ndn::L3Protocol> ndn, Ptr<NetDevice> device) { //NS LOG UNCOND ("Creating ndn::V2vNetDeviceFace on node"<< node->GetId() ); Ptr < ndn::NetDeviceFace > face = CreateObject < ndn::V2vNetDeviceFace > (node, device); NS_LOG_DEBUG("Node=" << node->GetId() << "MAC=" << device->GetAddress()); ndn->AddFace(face); return face; } voidprintPosition(Ptr<const MobilityModel>mobility) { NS LOG INFO("Time="<<Simulator::Now().GetSeconds( )<<"Positionof:"<< mobility->GetObject<Node>()->GetId()<<":"<<mobility->GetPosition()); } //------------------------------------// void ReceivePacket(Ptr<Socket> socket) { //NS LOG UNCOND ("Received one packet!"); packet_count++; } int main(int argc, char* argv[]) { //NS LOG UNCOND( "NDN SIMULATION ---->Started<----"); std::stringphyMode("OfdmRate6Mbps"); //("DsssRate1Mbps"); double rss = -80; // -dBm uint32_t packet Size = 512; // bytes uint32_t numPackets = 50; // double interval=0.5;//seconds bool verbose = false; //Param for simulation and tracing bool pcapOn = true; // Tracing is enabled by default uint32_t numberOfConsumer = 1; // D a f ault value:1 uint32_t numberOfProducer = 1; //Default value:1 uint32_t numberOfRuns = 50; //Default value:50 uint32_t numOfNodes = 357; //Default value:12 std::string mobFile("/home/user/Desktop/ndnSIM/ns-3/scratch/losangeles.cc"); double time = 0; double x = 0, y = 0, z = 0; int nodeNo = 0; CommandLine cmd; cmd.AddValue("phyMode", "Wifi Phy mode", phyMode); cmd.AddValue("rss", "received signal strength", rss); cmd.AddValue("packet Size", " size of application packet sent", packetSize); cmd.AddValue("numPackets ", "number of packets generated", numPackets); //cmd . AddValue("interval","interval(seconds) between packets",interval); cmd.AddValue("verbose"," turn on all WifiNetDevice log components",verbose) ; //new param cmd.AddValue("pcapOn","Turn on/off pcap tracing.Tracing is enabled by default",pcapOn); cmd.AddValue("numConsumer","Number of consumer in the simulation",numberOfConsumer); cmd.AddValue("numProducer","Number of producer in the simulation",numberOfProducer); cmd.AddValue("numRun", "Number of run per simulation",numberOfRuns); cmd.AddValue("mobilityFile", "Insertfullpath", mobFile); cmd.AddValue("numNodes"," Total number o f nodes in the simulation",numOfNodes); cmd.Parse(argc, argv); // Convert to time object //Time inter Packet Interval= Seconds (interval); // NS LOG UNCOND("true"); //disable fragmentation for frames below 2200 bytes Config::SetDefault( "ns3::WifiRemoteStationManager::FragmentationThreshold ", StringValue("2200")); // turn off RTS/CTS for frames below 2200bytes Config::SetDefault( "ns3::WifiRemoteStationManager::RtsCtsThreshold ", StringValue("2200")); // Fix non-unicast data rate to be the same as that of unicast Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",String Value(phyMode)); //enable cache unsolicited Data Config::SetDefault( "ns3::ndn::ForwardingStrategy::CacheUnsolicitedData", BooleanValue(true)); //Read number of cars directly from file std::ifstreamreadNcars; std::map<int, int> map count; int count = 0; readNcars.open(mobFile.cstr(), std::ios::in); while (readNcars >> nodeNo) { readNcars >> time >> x >> y >> z; if (mapcount.find(nodeNo) != mapcount.end()) { // cout<<"Ke yis present:"<<nodeNo<<" is present!\n"; count = mapcount[nodeNo]; count++; mapcount[nodeNo] = count; } else { // cout <<"Key not present:"<<nodeNo<<"is not present!\n"; mapcount[nodeNo] = 1; } } numOfNodes = map count.size(); NodeContainer c; c.Create(numOfNodes); // The below set of helpers will help us to put together th e wifi NICs we want WifiHelperwifi; if (verbose) { wifi.EnableLogComponents(); // Turn on all Wifi logging } wifi.SetStandard ( WIFI PHY STANDARD 80211a); //WIFI PHY STANDARD 80211b YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default(); // This is one parameter that matters when using FixedRssLossModel // set it to zero;otherwise, gain will be added wifiPhy.Set("RxGain ", DoubleValue(0)); wifiPhy.Set("EnergyDetectionThreshold", DoubleValue(-93)); //dBm,default value is -96 dBm // ns-3 supports RadioTap and Prism tracing extensions for 802.11b wifiPhy.SetPcapDataLinkType( YansWifiPhyHelper::DLTIEEE80211RADIO); YansWifiChannelHelperwifiChannel; wifiChannel.SetPropagationDelay( "ns3::ConstantSpeedPropagationDelayModel "); // Proptagation model is CORNER wifiChannel.AddPropagationLoss( "ns3::CornerPropagationLossModel"); wifiPhy.SetChannel(wifiChannel.Create()); // Add a non-QoS upper mac,and disablerate control NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default(); wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode ", StringValue(phyMode), "ControlMode", StringValue(phyMode)); // Set it to adhoc mode wifiMac.SetType("ns3::AdhocWifiMac"); NetDeviceContainerdevices = wifi.Install(wifiPhy, wifiMac, c); // Create file for thecapture if(pcapOn==true) { //wifiPhy.EnablePcap("capture examp",devices); //wifiPhy.EnablePcap Internal("captureexampnode0",devices.Get(0),true); //wifiPhy.Enable Pcap Internal("captureexampnode1",devices.Get(0),true);} //the format of corner.mobility //NodeNum time x y z // by reading each line ,we can get a detaile dtrace of nodes ’ mobility MobilityHelper mobility; mobility.SetMobilityModel("ns3::WaypointMobilityModel"); mobility.Install(c); std::ifstream mobileInput; mobileInput.open(mobFile.cstr(),std::ios::in); if(!mobileInput.isopen()) { NS LOG ERROR("Invalidmap.The path("<<mobFile<<"is wrong.Please check it again"); return -1; } //With map std::map<int,Ptr<WaypointMobilityModel>>wayMobility; //NS LOG UNCOND ( " nNodes = "<<nNodes ) ; uint32_t indexc=0; for(std::map<int,int>::iteratorit=mapcount.begin(); it!=mapcount.end();it++,indexc++) { wayMobility[it ->first]=c.Get(indexc)->GetObject<WaypointMobilityModel >(); // cout <<"Key="<<it->first<<"Value="<<it-> second <<"\n "; } // setting initial position to all the nodes.We put all the cars far away from the map (100Km +some randomvalue) double sinkX =100000; double sinkY = 100000; double sinkZ =0; index c = 0; for (std::map<int,int>::iteratorit=map count.begin(); it!=mapcount.end();it++,indexc++) { Waypoint waypoint(Seconds(0.1),Vector3D(sinkX+(indexc *10000),sinkY+(indexc *10000),sinkZ)); // wayMobility [ i ]->AddWaypoint (waypoint); Simulator::Schedule(Seconds(0.1),&WaypointMobilityModel::SetPosition,wayMobility[it->first],Vector3D(sinkX+(indexc*10000),sinkY+(indexc*10000),sinkZ) ); } std::map<int,int>endTime; for(std::map<int,int>::iteratorit=mapcount.begin(); it != map count.end();it++) { endTime[it->first]=0; } while(mobileInput>>nodeNo) { mobileInput>>time>>x>>y>>z; if(time <=0.1) { //discarding the positionatsec0; we ’ ve substituted them with sink coordinates continue; } endTime[nodeNo]=time; Waypoint waypoint(Seconds (time),Vector3D(x,y,z)); //NS LOG UNCOND( "Reading mobility file Id="<< nodeNo<<" time="<<time<<"("<<x<<","<<y<<")"); wayMobility[nodeNo]->AddWaypoint(waypoint); /*if(nodeNo==0) { wayMobility0->AddWaypoint ( waypoint );} else if(nodeNo==1) { wayMobility1->AddWaypoint(waypoint); }*/ } //std::vector<Ptr<Node>>::constiterator it=c.Begin(); //setting sink coordinates when a car mobility terminates uint32_t numberOfWaypoint; Waypoint point; for(std::map<int,int>::iteratorit=map count.begin(); it!=mapcount.end();it ++) {numberOfWaypoint = wayMobility[it->first]->WaypointsLeft(); //TO DO chec kif it goes to the last element if(numberOfWaypoint==0) { continue; } index c = 0; Simulator::Schedule(Seconds(endTime[it->first]+0.0001),&WaypointMobilityModel::SetPosition,wayMobility[it->first],Vector3D (sinkX+(indexc*10000),sinkY+(indexc*10000),sinkZ));} //NS LOG UNCOND ("Mobility read!") ; // Install Ndn stack on all nodes //NS LOG INFO ( " Installing Ndnstack ") ; ndn::StackHelperndnHelper; EndnHelper.AddNetDeviceFaceCreateCallback ( WifiNetDevice : : GetTypeId ( ),MakeCallback(V2vNetDeviceFaceCallback ) ); //...setting ad hoc forwarding ndnHelper.SetForwardingStrategy("ns3::ndn::fw::V2v"); ndnHelper.SetDefaultRoutes(true); ndnHelper.InstallAll( ); // Test with more than one consumer std::ifstream fileConsumer; fileConsumer.open("/home/nrl/contolic/vndn-sim/ns-3/scratch/consumer.txt",std::ios::in); if ( !fileConsumer.is open () ) { NS LOG ERROR("Invalidname.The name"<<fileConsumer<<"is wrong.Please check it again"); return -1; } int idConsumer = 0; int countCons = 0; int indexCNodes = numOfNodes - 1; while(fileConsumer>>idConsumer ) { //NS LOG UNCOND( " idConsumer " << idConsumer ) ; std::string consumerName=" c"+idConsumer; Ptr<Node> nodeConsumer = CreateObject <Node >(); //Names : : Add( consumerName , nodeConsumer ) ; ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr"); consumerHelper.SetPrefix("/prefix"); consumerHelper.SetAttribute(" Frequency ",StringValue ("1")); consumerHelper.SetAttribute("Randomize",StringValue("uniform ")); ApplicationContainerconsumers=consumerHelper.Install(c.Get(indexCNodes-countCons)); consumers.Start(Seconds(50));//(50)-countCons *10 consumers.Stop(Seconds(450));//(600)-30 countCons++; } // Test with more than oneproducer std::ifstream fileProducer; fileProducer.open("/home/nrl/contolic/vndn-sim/ns-3/scratch/producer.txt",std::ios::in); if(!fileProducer.is open () ) { NS LOG ERROR( "Invalidname.Thename"<<fileProducer<<"iswrong.Please check it again "); return -1; } int idProducer = 0; int countProd = 0; int indexPNodes = 0; while(fileProducer>>idProducer) { //NS LOG UNCOND("idProducer"<<idProducer); std::string producerName="c"+idProducer;Ptr<Node>nodeProducer=CreateObject<Node >(); //Names::Add(producerName,nodeProducer); ndn::AppHelperproducerHelper("ns3::ndn::Producer"); producerHelper.SetPrefix("/prefix" ); producerHelper.SetAttribute("PayloadSize",StringValue ("1024") ); ApplicationContainerproducers=producerHelper.Install(c.Get(indexPNodes+countProd)); //producers.Start(Seconds(countProd*0.5)); countProd++;} /*ndn::AppHelperproducerHelper("ns3::ndn::Producer"); // Producer willreply to all requestsstarting with/prefixproducerHelper.SetPrefix("/prefix"); producerHelper.SetAttribute(" PayloadSize ",StringValue("1024")); //ApplicationContainerproducers=producerHelper. Install(c.Get(0));// AlmostatLincolnBlvd on WilshireBlvd*/ //NS LOG UNCOND(" Applicationinstalled!!" ) ; // Trace oflevel2.5 Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacTx",MakeCallback(&MacTxCount)); Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRx",MakeCallback(&MacRxCount ) ); Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice /Mac/MacTxDrop",MakeCallback(&MacTxDrop)); Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRxDrop",MakeCallback(&MacRxDrop)); // Trace Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/OutInterests",MakeCallback(&OutInterest)); Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/InInterests",MakeCallback(&InInterest)); Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/DropInterests",MakeCallback(& DropInterest)); Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/InData ",MakeCallback(&InData)); Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/DropData ",MakeCallback(&DropData )); Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/OutData",MakeCallback(&OutData ) ); /* Tracing the car position*/ Config::ConnectWithoutContext("/NodeList/*/$ns3::MobilityModel / CourseChange ",MakeCallback(&printPosition ) ); Simulator::Stop(Seconds(600.0));//(600.0)-30 /*Testingtraces*/ /* boost::tuple< boost::sharedptr<std::ostream >, std::list<Ptr<ndn::L3AggregateTracer> > > aggTracers= ndn::L3AggregateTracer::InstallAll("/ mnt/space/simulationlog/ndn-600s-aggregate-trace-v2v.txt",Seconds (0.5));*/ /* boost::tuple<boost::sharedptr<std::ostream >,std::list<Ptr<ndn::L3RateTracer> > > rateTracers=ndn::L3RateTracer::InstallAll("/mnt/space/simulationlog/ndn-600s-rate-trace-v2v.txt",Seconds(0.5));*/ /* boost::tuple<boost::sharedptr<std::ostream >, std::list<boost::sharedptr<ndn::V2vTracer> >>v2vtracing=ndn::V2vTracer::InstallAll("v2v.tracer.txt");*/ Simulator:: Run ( ); Simulator:: Destroy ( ); return 0; } also here is the second file ndn-v2v-net-device-face.h enter code here #ifndef NDN_V2V_NET_DEVICE_FACE_H #define NDN_V2V_NET_DEVICE_FACE_H #include "ns3/nstime.h" #include "ns3/event-id.h" #include "ns3/random-variable.h" #include "ns3/traced-callback.h" #include "ns3/ndn-net-device-face.h" #include "ns3/ndn-header-helper.h" namespace ns3 { class Vector3D; typedef Vector3D Vector; namespace ndn { class NameComponents; /** * \ingroup ndn-face * \brief Implementation of layer-2 broadcast vehicle-2-vehicle NDN face * * This class defines basic functionality of NDN face. Face is core * component responsible for actual delivery of data packet to and * from NDN stack * * ndn::NetDevice face is permanently associated with one NetDevice * object and this object cannot be changed for the lifetime of the * face * * The only difference from the base class is that ndn::V2vNetDevice * makes additional consideration for overheard information * * \see ndn::AppFace, ndn::NetDeviceFace */ class V2vNetDeviceFace : public NetDeviceFace { public: static TypeId GetTypeId (); /** * \brief Constructor * * \param netDevice a smart pointer to NetDevice object to which * this face will be associate */ V2vNetDeviceFace (Ptr<Node> node, const Ptr<NetDevice> &netDevice); virtual ~V2vNetDeviceFace(); // from CcnxFace virtual void SendLowPriority (Ptr<Packet> p); protected: // from ndn::NetDeviceFace virtual bool SendImpl (Ptr<Packet> p); public: virtual std::ostream& Print (std::ostream &os) const; private: V2vNetDeviceFace (const V2vNetDeviceFace &); ///< \brief Disabled copy constructor V2vNetDeviceFace& operator= (const V2vNetDeviceFace &); ///< \brief Disabled copy operator /// \brief callback from lower layers virtual void ReceiveFromNetDevice (Ptr<NetDevice> device, Ptr<const Packet> p, uint16_t protocol, const Address &from, const Address &to, NetDevice::PacketType packetType); void SendFromQueue (); void SetMaxDelay (const Time &value); Time GetMaxDelay () const; void SetMaxDelayLowPriority (const Time &value); Time GetMaxDelayLowPriority () const; void ProcessRetx (); Time GetPriorityQueueGap () const; void NotifyJumpDistanceTrace (const Ptr<const Packet> packet); private: struct Item { Item (const Time &_gap, const Ptr<Packet> &_packet); Item (const Item &item); Item & operator ++ (); Item & Gap (const Time &time); Time gap; Ptr<Packet> packet; HeaderHelper::Type type; Ptr<const NameComponents> name; uint32_t retxCount; }; typedef std::list<Item> ItemQueue; EventId m_scheduledSend; // Primary queue (for requested ContentObject packets) Time m_totalWaitPeriod; UniformVariable m_randomPeriod; Time m_maxWaitPeriod; uint32_t m_maxPacketsInQueue; ItemQueue m_queue; // Low-priority queue (for pushing Interest and ContentObject packets) Time m_maxWaitLowPriority; double m_maxDistance; ItemQueue m_lowPriorityQueue; // Retransmission queue for low-priority pushing EventId m_retxEvent; Time m_maxWaitRetransmission; ItemQueue m_retxQueue; uint32_t m_maxRetxAttempts; TracedCallback<double, double> m_waitingTimeVsDistanceTrace; TracedCallback<Ptr<const Node>, double> m_jumpDistanceTrace; TracedCallback<Ptr<Node>, Ptr<const Packet>, const Vector&> m_tx; TracedCallback<Ptr<Node>, Ptr<const Packet> > m_cancelling; }; } // namespace ndn } // namespace ns3 #endif // NDN_V2V_NET_DEVICE_FACE_H [1]: http://i.stack.imgur.com/kdiPk.png
0debug
static void handle_mousemotion(SDL_Event *ev) { int max_x, max_y; struct sdl2_console *scon = get_scon_from_window(ev->key.windowID); if (qemu_input_is_absolute() || absolute_enabled) { int scr_w, scr_h; SDL_GetWindowSize(scon->real_window, &scr_w, &scr_h); max_x = scr_w - 1; max_y = scr_h - 1; if (gui_grab && (ev->motion.x == 0 || ev->motion.y == 0 || ev->motion.x == max_x || ev->motion.y == max_y)) { sdl_grab_end(scon); } if (!gui_grab && (ev->motion.x > 0 && ev->motion.x < max_x && ev->motion.y > 0 && ev->motion.y < max_y)) { sdl_grab_start(scon); } } if (gui_grab || qemu_input_is_absolute() || absolute_enabled) { sdl_send_mouse_event(scon, ev->motion.xrel, ev->motion.yrel, ev->motion.x, ev->motion.y, ev->motion.state); } }
1threat
How to select users in the message table in mysql and order them by date? : I am building messaging module in mysql and PHP. I have a table in which I am saving the messages. The table for messages has the following colloums. Index | from | to | date | body Now I want to select the users who sent or recived text from a specfic user and order that by date. Please help me! If I am user 2, Table: Index | from | to | date | body 1 | user1 | user2 | 2018-06-18 12:51:19 | Hi 2 | user2 | user1 | 2018-06-18 12:55:19 | Hello 4 | user3 | user2 | 2018-06-18 12:55:19 | Hi 5 | user2 | user3 | 2018-06-18 12:56:19 | Hello 6 | user3 | user2 | 2018-06-19 01:55:19 | bolo 7 | user2 | user3 | 2018-06-19 02:56:19 | Kya If I am user 2, Desired data: user3 | 2018-06-19 02:56:19 user1 | 2018-06-18 12:55:19
0debug
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model, const char *default_devaddr) { const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr; PCIBus *bus; int devfn; PCIDevice *pci_dev; DeviceState *dev; int i; i = qemu_find_nic_model(nd, pci_nic_models, default_model); if (i < 0) return NULL; bus = pci_get_bus_devfn(&devfn, devaddr); if (!bus) { error_report("Invalid PCI device address %s for device %s", devaddr, pci_nic_names[i]); return NULL; } pci_dev = pci_create(bus, devfn, pci_nic_names[i]); dev = &pci_dev->qdev; if (nd->name) dev->id = qemu_strdup(nd->name); qdev_set_nic_properties(dev, nd); if (qdev_init(dev) < 0) return NULL; return pci_dev; }
1threat
static inline void vmsvga_copy_rect(struct vmsvga_state_s *s, int x0, int y0, int x1, int y1, int w, int h) { DisplaySurface *surface = qemu_console_surface(s->vga.con); uint8_t *vram = s->vga.vram_ptr; int bypl = surface_stride(surface); int bypp = surface_bytes_per_pixel(surface); int width = bypp * w; int line = h; uint8_t *ptr[2]; if (y1 > y0) { ptr[0] = vram + bypp * x0 + bypl * (y0 + h - 1); ptr[1] = vram + bypp * x1 + bypl * (y1 + h - 1); for (; line > 0; line --, ptr[0] -= bypl, ptr[1] -= bypl) { memmove(ptr[1], ptr[0], width); } } else { ptr[0] = vram + bypp * x0 + bypl * y0; ptr[1] = vram + bypp * x1 + bypl * y1; for (; line > 0; line --, ptr[0] += bypl, ptr[1] += bypl) { memmove(ptr[1], ptr[0], width); } } vmsvga_update_rect_delayed(s, x1, y1, w, h); }
1threat
Message: session_start(): Cannot send session cache limiter - headers already sent : <p>Having a problem with sessions which is becoming very annoying. Every time I try to start a session on a particular page I get the following error:</p> <p>Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/uplbcdcn/public_html/CDC/admin_uplbcdc/header.php:57) in /home/uplbcdcn/public_html/CDC/admin_uplbcdc/index.php on line 33</p> <p>Warning: Cannot modify header information - headers already sent by (output started at /home/uplbcdcn/public_html/CDC/admin_uplbcdc/header.php:57) in /home/uplbcdcn/public_html/CDC/admin_uplbcdc/index.php on line 42</p> <p>Here is the Code: header.php</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;UPLB Credit and Development Cooperative&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- Bootstrap --&gt; &lt;link href="../css/bootstrap.css" rel="stylesheet" media="screen"&gt; &lt;link href="../css/bootstrap-responsive.css" rel="stylesheet" media="screen"&gt; &lt;link href="../css/docs.css" rel="stylesheet" media="screen"&gt; &lt;link href="../css/diapo.css" rel="stylesheet" media="screen"&gt; &lt;link href="../css/font-awesome.css" rel="stylesheet" media="screen"&gt; &lt;link rel="stylesheet" type="text/css" href="../css/style.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="../css/DT_bootstrap.css" /&gt; &lt;link rel="stylesheet" type="text/css" media="print" href="../css/print.css" /&gt; &lt;!-- js --&gt; &lt;script src="../js/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script src="../js/bootstrap.js"&gt;&lt;/script&gt; &lt;script src="../js/jquery.hoverdir.js"&gt;&lt;/script&gt; &lt;script&gt; jQuery(document).ready(function() { $(function(){ $('.pix_diapo').diapo(); }); }); &lt;/script&gt; &lt;noscript&gt; &lt;style&gt; .da-thumbs li a div { top: 0px; left: -100%; -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } .da-thumbs li a:hover div{ left: 0px; } &lt;/style&gt; &lt;/noscript&gt; &lt;script type="text/javascript" charset="utf-8" language="javascript" src="../js/jquery.dataTables.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8" language="javascript" src="../js/DT_bootstrap.js"&gt;&lt;/script&gt; &lt;script type='text/javascript' src='../scripts/jquery.easing.1.3.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='../scripts/jquery.hoverIntent.minified.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='../scripts/diapo.js'&gt;&lt;/script&gt; &lt;!--sa calendar--&gt; &lt;script type="text/javascript" src="../js/datepicker.js"&gt;&lt;/script&gt; &lt;link href="../css/datepicker.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;?php include('dbcon.php'); ?&gt; &lt;body&gt; index.php &lt;?php include('header.php'); ?&gt; &lt;?php include('navbar.php'); ?&gt; &lt;div class="container"&gt; &lt;div class="margin-top"&gt; &lt;div class="row"&gt; &lt;div class="span12"&gt; &lt;div class="login"&gt; &lt;div class="log_txt"&gt; &lt;p&gt;&lt;strong&gt;Please Enter the Details Below..&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;form class="form-horizontal" method="POST"&gt; &lt;div class="control-group"&gt; &lt;label class="control-label" for="inputEmail"&gt;Username&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="text" name="username" id="username" placeholder="Username" required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;label class="control-label" for="inputPassword"&gt;Password&lt;/label&gt; &lt;div class="controls"&gt; &lt;input type="password" name="password" id="password" placeholder="Password" required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;button id="login" name="submit" type="submit" class="btn"&gt;&lt;i class="icon-signin icon-large"&gt;&lt;/i&gt;&amp;nbsp;Submit&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php if (isset($_POST['submit'])){ session_start(); $username = $_POST['username']; $password = $_POST['password']; mysqli_select_db($dbcon,$database_dbcon); $query = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = mysqli_query($dbcon,$query)or die(mysqli_error()); $num_row = mysqli_num_rows($result); $row=mysqli_fetch_array($result); if( $num_row &gt; 0 ) { header('location:dashboard.php'); $_SESSION['id']=$row['user_id']; } else{ ?&gt; &lt;div class="alert alert-danger"&gt;Access Denied&lt;/div&gt; &lt;?php }} ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php include('footer.php') ?&gt; </code></pre>
0debug
Is there a cross language standard? Ie C++ to Java over serial? : <p>For my project, I am creating an Android GUI app to control settings on a Arduino. There is a USB OTG cable bridging the smartphone and the arduino. At the current state, the arduino replies back strings that were initially sent from the App to demonstrate successful communication.</p> <p>However as the app will allow the user to changing settings, I was wondering if there is a guideline to help with moulding this communication between the two languages?</p> <p>At the current time, I visualized that I could facilitate this communication by setting a certain word for certain settings then followed up by the number to set the correct setting.</p> <p>Ie, 50 second timer could be designated by TIMER50S which allows the arduino to parse the string and decipher that the timer needs to be set to 50 seconds. </p> <p>I was wondering if there was a well established standard to communication protocols like these?</p>
0debug
How to access BLE on Raspberry Pi 3 using Java? : <p>The Raspberry Pi 3 includes BLE support. I confirmed it works by </p> <p>sudo hcitool lescan</p> <p>which returned the MAC and BLE 'complete local name' for neighboring advertisers.</p> <p>How does one access this programmatically, in Java?</p>
0debug
av_cold void ff_ps_ctx_init(PSContext *ps) { ipdopd_reset(ps->ipd_hist, ps->opd_hist); }
1threat
How can I create a 10-megabyte binary file on linux? : <p>I want to create the file to implement a I/O benchmark on linux.</p> <p>Thanks in advance, Antonio</p>
0debug
void spapr_core_release(DeviceState *dev) { MachineState *ms = MACHINE(qdev_get_hotplug_handler(dev)); sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(ms); CPUCore *cc = CPU_CORE(dev); CPUArchId *core_slot = spapr_find_cpu_slot(ms, cc->core_id, NULL); if (smc->pre_2_10_has_unused_icps) { sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev)); sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc)); size_t size = object_type_get_instance_size(scc->cpu_type); int i; for (i = 0; i < cc->nr_threads; i++) { CPUState *cs = CPU(sc->threads + i * size); pre_2_10_vmstate_register_dummy_icp(cs->cpu_index); } } assert(core_slot); core_slot->cpu = NULL; object_unparent(OBJECT(dev)); }
1threat
static int bdrv_prwv_co(BdrvChild *child, int64_t offset, QEMUIOVector *qiov, bool is_write, BdrvRequestFlags flags) { Coroutine *co; RwCo rwco = { .child = child, .offset = offset, .qiov = qiov, .is_write = is_write, .ret = NOT_DONE, .flags = flags, }; if (qemu_in_coroutine()) { bdrv_rw_co_entry(&rwco); } else { AioContext *aio_context = bdrv_get_aio_context(child->bs); co = qemu_coroutine_create(bdrv_rw_co_entry); qemu_coroutine_enter(co, &rwco); while (rwco.ret == NOT_DONE) { aio_poll(aio_context, true); } } return rwco.ret; }
1threat
error: non-static variable average cannot be referenced from a static context : <p>Write a program to input marks of three subjects for a student and calculate the average marks. In your class. a) Include a constructor to initialize the three marks to 0 b) Include a method to calculate and store the average c) Include a method to display the student ID,name and the average marks of the student</p> <pre><code>import java.util.Scanner; public class Main{ int mark1; int mark2; int mark3; float total; float average; public Main(){ int mark1=50; int mark2=60; int mark3=70; float total=0; float average=0; } public static void main(String args[]){ Main myb = new Main(); Scanner my = new Scanner(System.in); System.out.println("Enter marks for First subject"); int marks1 = my.nextInt(); System.out.println("Enter marks for Second subject"); int marks2 = my.nextInt(); System.out.println("Enter marks for Third subject"); int marks3 = my.nextInt(); total = marks1+marks2+marks3; average = total/3; System.out.println("Total is "+myb.total); System.out.println("Total is "+myb.average); /*Student stud1=new Student("IT9087567","Kamal",50,60,70); stud1.showDetail();*/ } } </code></pre>
0debug
Stack Implementation in Java : <p>I'm trying to implement a stack using Arrays in Java. My Stack class consists of non static methods push, pop, peek and isempty. I want to test the stack implementation be instantiating the stack in a non static main method within a main class. When I try to do that I get an error <strong>"non-static method push(int) cannot be referenced from a static context"</strong> What am I doing wrong ?</p> <p>Stack.java</p> <pre><code>public class Stack { private int top; private int[] storage; Stack(int capacity){ if (capacity &lt;= 0){ throw new IllegalArgumentException( "Stack's capacity must be positive"); } storage = new int[capacity]; top = -1; } void push(int value){ if (top == storage.length) throw new EmptyStackException(); top++; storage[top] = value; } int peek(){ if (top == -1) throw new EmptyStackException(); return storage[top]; } int pop(){ if (top == -1) throw new EmptyStackException(); return storage[top]; } } </code></pre> <p>Main.java</p> <pre><code>public class Main { public static void main(String[] args) { new Stack(5); Stack.push(5); System.out.println(Stack.pop()); } } </code></pre>
0debug
Backup core data locally, and restore from backup - Swift : <p>I'm struggling to find any information about creating backups of core data. My ultimate goal is to allow the user to create multiple backups, and restore from a selected backup. </p> <p>I've found a sample project that allows you backup/restore locally or via iCloud in Objective-C, but nothing in swift.</p> <p>Can anyone help? Or point me in the right direction. I don't even know where to start with this one. </p>
0debug
print object value from XML in PHP : <p>I need to read rss feed and then re-create feeds as it is.<br> If there is 10 item I just need 3. But I want to define which one. first 3 or last 3 or middle. After this I need to show only 3 item in feed. But feed most as it was previous one. Only my purpose is to split Feed.<br> Here what I'm using but it's not working. </p> <pre><code>&lt;?php header("Content-Type: application/rss+xml; charset=ISO-8859-1"); echo '&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;rss version="2.0"&gt;'; $url_number = $_GET['u']; $offset = $_GET['o']; $limit = $_GET['l']; $url = 'url_of_the_feed'; $feed = simplexml_load_file($url); echo "&lt;channel&gt;". (string) $feed-&gt;channel. "&lt;/channel&gt;"; $i = 1; foreach($feed-&gt;channel-&gt;item as $item){ if($i &gt;= $offset &amp;&amp; $i &lt;= $limit){ echo "&lt;item&gt;" . $item . "&lt;/item&gt;"; } if($i == $limit){ break; } $i++; } echo "&lt;/channel&gt;&lt;/rss&gt;"; ?&gt; </code></pre> <p>This is not printing anything inside channel and item.</p>
0debug
How to update or add an Environment Variable to a TeamCity agent : <p>TeamCity agent's show a list of "Environment Variables" under Agent Parameters but I cannot get them to update. I've added environment variables to my agent operating system, but cannot get them to refresh. I've tried restarting the agent and disabling and re-enabling the agent.</p>
0debug
static void slirp_hostfwd(SlirpState *s, Monitor *mon, const char *redir_str, int legacy_format) { struct in_addr host_addr = { .s_addr = INADDR_ANY }; struct in_addr guest_addr = { .s_addr = 0 }; int host_port, guest_port; const char *p; char buf[256]; int is_udp; char *end; p = redir_str; if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (!strcmp(buf, "tcp") || buf[0] == '\0') { is_udp = 0; } else if (!strcmp(buf, "udp")) { is_udp = 1; } else { goto fail_syntax; } if (!legacy_format) { if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) { goto fail_syntax; } } if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) { goto fail_syntax; } host_port = strtol(buf, &end, 0); if (*end != '\0' || host_port < 1 || host_port > 65535) { goto fail_syntax; } if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) { goto fail_syntax; } guest_port = strtol(p, &end, 0); if (*end != '\0' || guest_port < 1 || guest_port > 65535) { goto fail_syntax; } if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr, guest_port) < 0) { config_error(mon, "could not set up host forwarding rule '%s'\n", redir_str); } return; fail_syntax: config_error(mon, "invalid host forwarding rule '%s'\n", redir_str); }
1threat
udp_attach(struct socket *so) { if((so->s = socket(AF_INET,SOCK_DGRAM,0)) != -1) { so->so_expire = curtime + SO_EXPIRE; insque(so, &so->slirp->udb); } return(so->s); }
1threat
apache tomcat 9.x not working with eclipse & Java 10.0.1 : <p>I've installed apache-tomcat-<strong>9.0.7</strong> on my windows machine and have following environment configurations:</p> <p>echo %JAVA_HOME% </p> <p>C:\Program Files\Java\ <strong>jdk-10.0.1</strong></p> <hr> <p>echo %JRE_HOME%</p> <p>C:\Program Files\Java\ <strong>jre-10.0.1</strong></p> <hr> <p>OS : <strong>Windows 8 64-bit</strong></p> <hr> <p>Eclipse Version: <strong>Oxygen.3a</strong> Release (4.7.3a)</p> <hr> <p>Whenever I run <code>catlina.bat start</code> from <strong>cmd</strong>, server runs fine on localhost But I'm not able to get the server instance up from eclipse's server configuration.</p> <ol> <li>Defined a new server in eclipse and added apache-tomact 9.0 instance</li> <li><p>Upon clicking on start server , I get the following error:</p> <p><em>-Djava.endorsed.dirs=C:\Softwares\apache-tomcat-9.0.7\endorsed is not supported</em>. <code>Endorsed standards and standalone APIs in modular form will be supported via the concept of upgradeable modules</code>.</p></li> </ol> <p><a href="https://i.stack.imgur.com/IPmNo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IPmNo.png" alt="Error Screen"></a></p> <p>Any solution for this issue ?</p>
0debug
void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new) { assert(!bdrv_requests_pending(old)); assert(!bdrv_requests_pending(new)); bdrv_ref(old); change_parent_backing_link(old, new); bdrv_unref(old); }
1threat
static void vga_isa_realizefn(DeviceState *dev, Error **errp) { ISADevice *isadev = ISA_DEVICE(dev); ISAVGAState *d = ISA_VGA(dev); VGACommonState *s = &d->state; MemoryRegion *vga_io_memory; const MemoryRegionPortio *vga_ports, *vbe_ports; vga_common_init(s, OBJECT(dev), true); s->legacy_address_space = isa_address_space(isadev); vga_io_memory = vga_init_io(s, OBJECT(dev), &vga_ports, &vbe_ports); isa_register_portio_list(isadev, 0x3b0, vga_ports, s, "vga"); if (vbe_ports) { isa_register_portio_list(isadev, 0x1ce, vbe_ports, s, "vbe"); } memory_region_add_subregion_overlap(isa_address_space(isadev), 0x000a0000, vga_io_memory, 1); memory_region_set_coalescing(vga_io_memory); s->con = graphic_console_init(DEVICE(dev), 0, s->hw_ops, s); vga_init_vbe(s, OBJECT(dev), isa_address_space(isadev)); rom_add_vga(VGABIOS_FILENAME); }
1threat
Javascript Regex - to fetch specific html tag from a string of tags : <p>I have a string which contains HTML TD tags. I want to construct a regex to fetch that TD which has innerHTML "Number" </p> <p>Example:</p> <p>Following are the whole string</p> <pre><code>var rows = `&lt;td width="69" style="white-space:normal"&gt;Name&lt;/td&gt; &lt;td width="70" style="white-space:normal;border-left:none"&gt;Number&lt;/td&gt; &lt;td width="64" style="white-space:normal;border-left:none"&gt;Type&lt;/td&gt;`; </code></pre> <p>Regex should be: If I put "Number" in regex, second TD tag should fetched. If I put "Name", first TD tag should fetched.</p> <p>Thank you,</p>
0debug
How to show spinner in angular 6 : <p>I am new to angular and web development but able to design various web pages and got data from the server using HTTP client module.</p> <p>While getting data from server I want to show progress spinner, but I am not able to do it. I have searched google but nothing made me to do it. Please help me to achieve this.</p> <p>Code:</p> <p>login.component.ts</p> <pre><code> userLogin() { console.log('logging in'); this.eService.signIn(this.user_name, this.password) .subscribe( data =&gt; { console.log(data); this.admin = data; if ( this.admin.firstLogin === true) { // go to update admin password } else { this.router.navigate(['/dashboard']); } localStorage.setItem('isLoggedin', 'true'); } ); } </code></pre> <p>login.html</p> <pre><code>&lt;div class="login-page" [@routerTransition]&gt; &lt;div class="row justify-content-md-center"&gt; &lt;div class="col-md-4"&gt; &lt;img src="assets/images/logo.png" width="150px" class="user-avatar" /&gt; &lt;h1&gt;Users/h1&gt; &lt;form role="form"&gt; &lt;div class="form-content"&gt; &lt;div class="form-group"&gt; &lt;input type="text" name="username" [(ngModel)]="user_name" class="form-control input-underline input-lg" id="" placeholder="username"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="password" name="password" [(ngModel)]="password" (keyup.enter)="userLogin()" class="form-control input-underline input-lg" id="" placeholder="password"&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="btn rounded-btn" (click)="userLogin()"&gt; Log in &lt;/a&gt; &amp;nbsp; &lt;a class="btn rounded-btn" &gt;Clear&lt;/a&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So when I am requesting signIn service I want to show the spinner, Please help me, how can I do it?</p> <p>I know this is simple for many of the developers here, but for me It is getting somewhat tough.</p>
0debug
Is it possible to have a Discord Bot with multiple commands and the different commands change the same variable? : I am writing a Bot for Discord in javascript and I was wondering if it is possible for it to have multiple commands that change the same variable. So, I have two commands !addPoint and !subPoint. I want !addPoint to score++ and !subPoint to score--, but while having the var score declared somewhere that both functions can access it. Can this be done and how?
0debug
How to set a DynamoDB Map property value, when the map doesn't exist yet : <p>How do you "upsert" a property to a DynamoDB row. E.g. <code>SET address.state = "MA"</code> for some item, when <code>address</code> does not yet exist?</p> <p>I feel like I'm having a chicken-and-egg problem because DynamoDB doesn't let you define a sloppy schema in advance.</p> <p>If <code>address</code> DID already exist on that item, of type <code>M</code> (for Map), the internet tells me I could issue an UpdateExpression like:</p> <p><code>SET #address.#state = :value</code></p> <p>with <code>#address</code>, <code>#state</code>, and <code>:value</code> appropriately mapped to <code>address</code>, <code>state</code>, and <code>MA</code>, respectively.</p> <p>But if the <code>address</code> property does <strong>not</strong> already exist, this gives an error:</p> <p>''' ValidationException: The document path provided in the update expression is invalid for update '''</p> <p>So.. it appears I either need to:</p> <ol> <li>Figure out a way to "upsert" <code>address.state</code> (e.g., <code>SET address = {}; SET address.state = 'MA'</code> in a single command)</li> </ol> <p>or</p> <ol start="2"> <li>Issue three (!!!) roundtrips in which I try it, <code>SET address = {};</code> on failure, and then try it again.</li> </ol> <p>If the latter.... how do I set a blank map?!?</p> <p>Ugh.. I like Dynamo, but unless I'm missing something obvious this is a bit crazy..</p>
0debug
Event evt and Event event : <p>I'm trying to understand the difference between these two arguments, Event event and Event evt. </p> <p>When do I use Event event and when do I use Event evt? </p> <p>Thanks. </p>
0debug
alert('Hello ' + user_input);
1threat
static int vhdx_create_new_region_table(BlockDriverState *bs, uint64_t image_size, uint32_t block_size, uint32_t sector_size, uint32_t log_size, bool use_zero_blocks, VHDXImageType type, uint64_t *metadata_offset) { int ret = 0; uint32_t offset = 0; void *buffer = NULL; uint64_t bat_file_offset; uint32_t bat_length; BDRVVHDXState *s = NULL; VHDXRegionTableHeader *region_table; VHDXRegionTableEntry *rt_bat; VHDXRegionTableEntry *rt_metadata; assert(metadata_offset != NULL); s = g_new0(BDRVVHDXState, 1); s->chunk_ratio = (VHDX_MAX_SECTORS_PER_BLOCK) * (uint64_t) sector_size / (uint64_t) block_size; s->sectors_per_block = block_size / sector_size; s->virtual_disk_size = image_size; s->block_size = block_size; s->logical_sector_size = sector_size; vhdx_set_shift_bits(s); vhdx_calc_bat_entries(s); buffer = g_malloc0(VHDX_HEADER_BLOCK_SIZE); region_table = buffer; offset += sizeof(VHDXRegionTableHeader); rt_bat = buffer + offset; offset += sizeof(VHDXRegionTableEntry); rt_metadata = buffer + offset; region_table->signature = VHDX_REGION_SIGNATURE; region_table->entry_count = 2; rt_bat->guid = bat_guid; rt_bat->length = ROUND_UP(s->bat_entries * sizeof(VHDXBatEntry), MiB); rt_bat->file_offset = ROUND_UP(VHDX_HEADER_SECTION_END + log_size, MiB); s->bat_offset = rt_bat->file_offset; rt_metadata->guid = metadata_guid; rt_metadata->file_offset = ROUND_UP(rt_bat->file_offset + rt_bat->length, MiB); rt_metadata->length = 1 * MiB; *metadata_offset = rt_metadata->file_offset; bat_file_offset = rt_bat->file_offset; bat_length = rt_bat->length; vhdx_region_header_le_export(region_table); vhdx_region_entry_le_export(rt_bat); vhdx_region_entry_le_export(rt_metadata); vhdx_update_checksum(buffer, VHDX_HEADER_BLOCK_SIZE, offsetof(VHDXRegionTableHeader, checksum)); ret = vhdx_create_bat(bs, s, image_size, type, use_zero_blocks, bat_file_offset, bat_length); if (ret < 0) { goto exit; } ret = bdrv_pwrite(bs, VHDX_REGION_TABLE_OFFSET, buffer, VHDX_HEADER_BLOCK_SIZE); if (ret < 0) { goto exit; } ret = bdrv_pwrite(bs, VHDX_REGION_TABLE2_OFFSET, buffer, VHDX_HEADER_BLOCK_SIZE); if (ret < 0) { goto exit; } exit: g_free(s); g_free(buffer); return ret; }
1threat
static void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv, ebml_master master) { uint8_t *buf, crc[4]; int size; if (pb->seekable) { size = avio_close_dyn_buf(*dyn_cp, &buf); if (mkv->write_crc && mkv->mode != MODE_WEBM) { AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf, size) ^ UINT32_MAX); put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc)); } avio_write(pb, buf, size); end_ebml_master(pb, master); } else { end_ebml_master(*dyn_cp, master); size = avio_close_dyn_buf(*dyn_cp, &buf); avio_write(pb, buf, size); } av_free(buf); *dyn_cp = NULL; }
1threat
static int qemu_calculate_timeout(void) { #ifndef CONFIG_IOTHREAD int timeout; if (!vm_running) timeout = 5000; else if (tcg_has_work()) timeout = 0; else { int64_t add; int64_t delta; delta = qemu_icount_delta(); if (delta > 0) { timeout = (delta + 999999) / 1000000; } else { add = qemu_next_deadline(); if (add > 10000000) add = 10000000; delta += add; qemu_icount += qemu_icount_round (add); timeout = delta / 1000000; if (timeout < 0) timeout = 0; } } return timeout; #else return 1000; #endif }
1threat
SharedPrefferences is saving only the last value : i try to use SharedPreferences but its only saving the last value. Main Activity ``` mypreference.setPrice(txtPrice.text.toString().toFloat()) mypreference.setSABV(txtABV.text.toString().toFloat()) ``` SharedPreference ``` class myPreferences(context: Context){ val PREFERENCENAME = "BeerNote" val PRICE = 0.0f val ALCOHOLBYVOLUME = 0.0f val preference = context.getSharedPreferences(PREFERENCENAME,Context.MODE_PRIVATE) fun setPrice(price:Float){ preference.edit().putFloat(PRICE.toString(),price).apply() } fun getPrice():Float{ return preference.getFloat(PRICE.toString(),0.0f) } fun setSABV(abv:Float){ preference.edit().putFloat(ALCOHOLBYVOLUME.toString(),abv).apply() } fun getABV():Float{ return preference.getFloat(ALCOHOLBYVOLUME.toString(),0.0f ) } } ``` when i try to recover the data ``` Toast.makeText(this, "Price:"+mypreference.getPrice(), Toast.LENGTH_LONG).show() Toast.makeText(this, "ABV:"+mypreference.getABV(), Toast.LENGTH_LONG).show() ``` only saves the ABV value in Price and ABV
0debug
static inline void doVertLowPass_altivec(uint8_t *src, int stride, PPContext *c) { uint8_t *src2 = src; const vector signed int zero = vec_splat_s32(0); const int properStride = (stride % 16); const int srcAlign = ((unsigned long)src2 % 16); DECLARE_ALIGNED(16, short, qp[8]) = {c->QP}; vector signed short vqp = vec_ld(0, qp); vector signed short vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7, vb8, vb9; vector unsigned char vbA0, vbA1, vbA2, vbA3, vbA4, vbA5, vbA6, vbA7, vbA8, vbA9; vector unsigned char vbB0, vbB1, vbB2, vbB3, vbB4, vbB5, vbB6, vbB7, vbB8, vbB9; vector unsigned char vbT0, vbT1, vbT2, vbT3, vbT4, vbT5, vbT6, vbT7, vbT8, vbT9; vector unsigned char perml0, perml1, perml2, perml3, perml4, perml5, perml6, perml7, perml8, perml9; register int j0 = 0, j1 = stride, j2 = 2 * stride, j3 = 3 * stride, j4 = 4 * stride, j5 = 5 * stride, j6 = 6 * stride, j7 = 7 * stride, j8 = 8 * stride, j9 = 9 * stride; vqp = vec_splat(vqp, 0); src2 += stride*3; #define LOAD_LINE(i) \ perml##i = vec_lvsl(i * stride, src2); \ vbA##i = vec_ld(i * stride, src2); \ vbB##i = vec_ld(i * stride + 16, src2); \ vbT##i = vec_perm(vbA##i, vbB##i, perml##i); \ vb##i = \ (vector signed short)vec_mergeh((vector unsigned char)zero, \ (vector unsigned char)vbT##i) #define LOAD_LINE_ALIGNED(i) \ vbT##i = vec_ld(j##i, src2); \ vb##i = \ (vector signed short)vec_mergeh((vector signed char)zero, \ (vector signed char)vbT##i) if (properStride && srcAlign) { LOAD_LINE_ALIGNED(0); LOAD_LINE_ALIGNED(1); LOAD_LINE_ALIGNED(2); LOAD_LINE_ALIGNED(3); LOAD_LINE_ALIGNED(4); LOAD_LINE_ALIGNED(5); LOAD_LINE_ALIGNED(6); LOAD_LINE_ALIGNED(7); LOAD_LINE_ALIGNED(8); LOAD_LINE_ALIGNED(9); } else { LOAD_LINE(0); LOAD_LINE(1); LOAD_LINE(2); LOAD_LINE(3); LOAD_LINE(4); LOAD_LINE(5); LOAD_LINE(6); LOAD_LINE(7); LOAD_LINE(8); LOAD_LINE(9); } #undef LOAD_LINE #undef LOAD_LINE_ALIGNED { const vector unsigned short v_2 = vec_splat_u16(2); const vector unsigned short v_4 = vec_splat_u16(4); const vector signed short v_diff01 = vec_sub(vb0, vb1); const vector unsigned short v_cmp01 = (const vector unsigned short) vec_cmplt(vec_abs(v_diff01), vqp); const vector signed short v_first = vec_sel(vb1, vb0, v_cmp01); const vector signed short v_diff89 = vec_sub(vb8, vb9); const vector unsigned short v_cmp89 = (const vector unsigned short) vec_cmplt(vec_abs(v_diff89), vqp); const vector signed short v_last = vec_sel(vb8, vb9, v_cmp89); const vector signed short temp01 = vec_mladd(v_first, (vector signed short)v_4, vb1); const vector signed short temp02 = vec_add(vb2, vb3); const vector signed short temp03 = vec_add(temp01, (vector signed short)v_4); const vector signed short v_sumsB0 = vec_add(temp02, temp03); const vector signed short temp11 = vec_sub(v_sumsB0, v_first); const vector signed short v_sumsB1 = vec_add(temp11, vb4); const vector signed short temp21 = vec_sub(v_sumsB1, v_first); const vector signed short v_sumsB2 = vec_add(temp21, vb5); const vector signed short temp31 = vec_sub(v_sumsB2, v_first); const vector signed short v_sumsB3 = vec_add(temp31, vb6); const vector signed short temp41 = vec_sub(v_sumsB3, v_first); const vector signed short v_sumsB4 = vec_add(temp41, vb7); const vector signed short temp51 = vec_sub(v_sumsB4, vb1); const vector signed short v_sumsB5 = vec_add(temp51, vb8); const vector signed short temp61 = vec_sub(v_sumsB5, vb2); const vector signed short v_sumsB6 = vec_add(temp61, v_last); const vector signed short temp71 = vec_sub(v_sumsB6, vb3); const vector signed short v_sumsB7 = vec_add(temp71, v_last); const vector signed short temp81 = vec_sub(v_sumsB7, vb4); const vector signed short v_sumsB8 = vec_add(temp81, v_last); const vector signed short temp91 = vec_sub(v_sumsB8, vb5); const vector signed short v_sumsB9 = vec_add(temp91, v_last); #define COMPUTE_VR(i, j, k) \ const vector signed short temps1##i = \ vec_add(v_sumsB##i, v_sumsB##k); \ const vector signed short temps2##i = \ vec_mladd(vb##j, (vector signed short)v_2, temps1##i); \ const vector signed short vr##j = vec_sra(temps2##i, v_4) COMPUTE_VR(0, 1, 2); COMPUTE_VR(1, 2, 3); COMPUTE_VR(2, 3, 4); COMPUTE_VR(3, 4, 5); COMPUTE_VR(4, 5, 6); COMPUTE_VR(5, 6, 7); COMPUTE_VR(6, 7, 8); COMPUTE_VR(7, 8, 9); const vector signed char neg1 = vec_splat_s8(-1); const vector unsigned char permHH = (const vector unsigned char){0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F}; #define PACK_AND_STORE(i) \ { const vector unsigned char perms##i = \ vec_lvsr(i * stride, src2); \ const vector unsigned char vf##i = \ vec_packsu(vr##i, (vector signed short)zero); \ const vector unsigned char vg##i = \ vec_perm(vf##i, vbT##i, permHH); \ const vector unsigned char mask##i = \ vec_perm((vector unsigned char)zero, (vector unsigned char)neg1, perms##i); \ const vector unsigned char vg2##i = \ vec_perm(vg##i, vg##i, perms##i); \ const vector unsigned char svA##i = \ vec_sel(vbA##i, vg2##i, mask##i); \ const vector unsigned char svB##i = \ vec_sel(vg2##i, vbB##i, mask##i); \ vec_st(svA##i, i * stride, src2); \ vec_st(svB##i, i * stride + 16, src2);} #define PACK_AND_STORE_ALIGNED(i) \ { const vector unsigned char vf##i = \ vec_packsu(vr##i, (vector signed short)zero); \ const vector unsigned char vg##i = \ vec_perm(vf##i, vbT##i, permHH); \ vec_st(vg##i, i * stride, src2);} if (properStride && srcAlign) { PACK_AND_STORE_ALIGNED(1) PACK_AND_STORE_ALIGNED(2) PACK_AND_STORE_ALIGNED(3) PACK_AND_STORE_ALIGNED(4) PACK_AND_STORE_ALIGNED(5) PACK_AND_STORE_ALIGNED(6) PACK_AND_STORE_ALIGNED(7) PACK_AND_STORE_ALIGNED(8) } else { PACK_AND_STORE(1) PACK_AND_STORE(2) PACK_AND_STORE(3) PACK_AND_STORE(4) PACK_AND_STORE(5) PACK_AND_STORE(6) PACK_AND_STORE(7) PACK_AND_STORE(8) } #undef PACK_AND_STORE #undef PACK_AND_STORE_ALIGNED } }
1threat
Will breaking a Windows 10 app into multiple exe's improve concurrency? : <p>I have a real time video processing application running on Windows 7/10 that has 4 distinct processing steps. Each of these steps is currently running in a WPF Task and I have eliminated copying of the video data as much as is possible, I am down to two copy operations. The capture of the video and the subsequent storing of the video is handled by a COM-based SDK. Would I see an increase in performance if I turned each of the steps into a separate exe and use a shared memory scheme to move the data between the exe's? Or rather than use WPF Tasks, use threads? Anyone have hard data on something like this?</p> <p>Thanks, Doug</p>
0debug
How to run multiple QTest classes? : <p>I have a subproject where I put all my <code>QTest</code> unit tests and build a stand-alone test application that runs the tests (i.e. I run it from within Qt Creator). I have multiple test classes that I can execute with <code>qExec()</code>. However I don't know what is the proper way to execute multiple test classes.</p> <p>Currently I do it in this way (MVCE):</p> <h2>tests.pro</h2> <pre><code>QT -= gui QT += core \ testlib CONFIG += console CONFIG -= app_bundle TEMPLATE = app TARGET = testrunner HEADERS += test_foo.h SOURCES += main.cpp </code></pre> <h2>main.cpp</h2> <pre><code>#include &lt;QtTest&gt; #include &lt;QCoreApplication&gt; #include "test_foo.h" int main(int argc, char** argv) { QCoreApplication app(argc, argv); TestFooClass testFoo; TestBarClass testBar; // NOTE THIS LINE IN PARTICULAR. return QTest::qExec(&amp;testFoo, argc, argv) || QTest::qExec(&amp;testBar, argc, argv); } </code></pre> <h2>test_foo.h</h2> <pre><code>#include &lt;QtTest&gt; class TestFooClass: public QObject { Q_OBJECT private slots: void test_func_foo() {}; }; class TestBarClass: public QObject { Q_OBJECT private slots: void test_func_bar() {}; }; </code></pre> <p>However the <a href="http://doc.qt.io/qt-5/qtest.html#qExec" rel="noreferrer">documentation for <code>qExec()</code></a> says this is the wrong way:</p> <blockquote> <p>For stand-alone test applications, this function should not be called more than once, as command-line options for logging test output to files and executing individual test functions will not behave correctly.</p> </blockquote> <p>The other major downside is that there is <strong>no single summary for all the test classes</strong>, only for individual classes. This is a problem when I have dozens of classes that each have dozens of tests. To check if all tests passed I have to scroll up to see all the "Totals" of what passed/failed of each class, e.g.:</p> <pre><code>********* Start testing of TestFooClass ********* PASS : TestFooClass::initTestCase() PASS : TestFooClass::test_func_foo() PASS : TestFooClass::cleanupTestCase() Totals: 3 passed, 0 failed, 0 skipped, 0 blacklisted ********* Finished testing of TestFooClass ********* ********* Start testing of TestBarClass ********* PASS : TestBarClass::initTestCase() PASS : TestBarClass::test_func_bar() PASS : TestBarClass::cleanupTestCase() Totals: 3 passed, 0 failed, 0 skipped, 0 blacklisted ********* Finished testing of TestBarClass ********* </code></pre> <p>I'm also surprised my <code>qExec() || qExec()</code> works considering that the <a href="http://doc.qt.io/qt-5/qtest.html#qExec" rel="noreferrer">documentation</a> says if a test failed <code>qExec()</code> returns a non-zero value, which should mean all the following <code>qExec()</code> calls wouldn't happen, but this seems not to be the case.</p> <p>What is the proper way to run multiple test classes? And so that I can see at a glance if any of the hundreds of unit tests I have have failed.</p>
0debug
Android Spinner - How to position dropdown arrow as close to text as possible when options have different length? : <p>The options in my spinner has different length and currently the dropdown arrow is positioned far to the right based on the longest option, as shown in the screenshot below.</p> <p><a href="https://i.stack.imgur.com/kt0ajm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kt0ajm.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/jPwEVm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jPwEVm.png" alt="enter image description here"></a></p> <p>Is it possible to move the dropdown arrow so that it is dynamically positioned based on currently selected option? </p> <p>Especially when the first option is just 'All', it looks weird when the dropdown arrow is so far away to the right.</p> <p>Referring to Google Translate App where dropdown arrow is always positioned next to its text: <a href="https://i.stack.imgur.com/IPMISm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IPMISm.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/paWgQm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/paWgQm.png" alt="enter image description here"></a></p>
0debug
What does this errormessage mean? : <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: com.juliandrach.eatfit, PID: 2223 java.lang.IllegalStateException: Could not find method aldirindersalami(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284) at android.view.View.performClick(View.java:4438) at android.view.View$PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Basically the error occurs when I am updating a variable by pressing a button and then trying to display the value of the variable with a toast in the same task.</p> <pre><code>public class Mahlzeiten extends AppCompatActivity { public static int proteine = 0; public static int carbs = 0; public static int fette = 0; public static int kcal = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mahlzeiten); String text = "Hallo" + proteine + "danke"; Toast.makeText(Mahlzeiten.this, text, Toast.LENGTH_SHORT).show(); } public void aldirindersalami (int proteine){ proteine++; // String text1 = "Hallo" + proteine + "danke"; // Toast.makeText(Mahlzeiten.this, text1, Toast.LENGTH_SHORT).show(); } } </code></pre>
0debug
Map modify array of objects in Swift 2.2 (3.0) : <p>I want to be able to modify my array of objects using <code>map</code> in Swift of the fly, without looping through each element.</p> <p>Before here were able to do something like this (Described in more details <a href="http://kelan.io/2016/mutating-arrays-of-structs-in-swift/" rel="noreferrer">here</a>:</p> <pre><code>gnomes = gnomes.map { (var gnome: Gnome) -&gt; Gnome in gnome.age = 140 return gnome } </code></pre> <p>Thanks for Erica Sadun and others, new proposals have gone through and we're now getting rid of C-style loops and using <code>var</code> inside the loop.</p> <p>In my case I'm first getting a warning to remove the <code>var</code> in then an error my <code>gnome</code> is a constant (naturally)</p> <p>My question is : How do we alter arrays inside a <code>map</code> or the new styled loops for that matter to be fully prepared for Swift 3.0?</p>
0debug
CSS Centering with Transform : <p>why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 50%? </p> <p>Working example:</p> <pre><code>span[class^="icon"] { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </code></pre> <p>Example that doesn't center:</p> <pre><code>span[class^="icon"] { position: absolute; top: 50%; right: 50%; transform: translate(-50%, -50%); } </code></pre>
0debug
static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent) { char desc[DESC_SIZE]; uint32_t cid; const char *p_name, *cid_str; size_t cid_str_size; BDRVVmdkState *s = bs->opaque; if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) { return 0; } if (parent) { cid_str = "parentCID"; cid_str_size = sizeof("parentCID"); } else { cid_str = "CID"; cid_str_size = sizeof("CID"); } if ((p_name = strstr(desc,cid_str)) != NULL) { p_name += cid_str_size; sscanf(p_name,"%x",&cid); } return cid; }
1threat
How to expose graphql field with different name : <p>I am exploring GraphQL and would like to know if there is any way of renaming the response field for example i have a POJO with these field</p> <pre><code>class POJO { Long id; String name; } </code></pre> <p>GraphQL query:</p> <pre><code>type POJO { id: Long name: String } </code></pre> <p>My response is something like this</p> <pre><code>{ "POJO" { "id": 123, "name": "abc" } } </code></pre> <p>Can i rename the name field to something like userName so that my response is below</p> <pre><code>{ "POJO" { "id": 123, "userName": "abc" } } </code></pre>
0debug
int qcow2_discard_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors, enum qcow2_discard_type type, bool full_discard) { BDRVQcow2State *s = bs->opaque; uint64_t end_offset; unsigned int nb_clusters; int ret; end_offset = offset + (nb_sectors << BDRV_SECTOR_BITS); offset = align_offset(offset, s->cluster_size); end_offset = start_of_cluster(s, end_offset); if (offset > end_offset) { return 0; } nb_clusters = size_to_clusters(s, end_offset - offset); s->cache_discards = true; while (nb_clusters > 0) { ret = discard_single_l2(bs, offset, nb_clusters, type, full_discard); if (ret < 0) { goto fail; } nb_clusters -= ret; offset += (ret * s->cluster_size); } ret = 0; fail: s->cache_discards = false; qcow2_process_discards(bs, ret); return ret; }
1threat
Using indexOf() in Switch Statement : <p>Need to set variable values using a Switch Statement based on a string being present in the URL. I've accomplished this by using if/then statements but I now need a "default" for var3. It would be cumbersome to write a final if/then statement that basically says that the final condition is met when none of the other strings are found in dom.url. </p> <p>Preferably, I'd want something like this: </p> <pre><code>if b.event_name ==="form_completion" { switch(b['dom.url'].indexOf(MYSTRING)) { case "Req-Quote-Thanks-Modal") &gt; -1: b.var1 = "VAL1"; b.var2 = "VAL2"; b.var3 = "VAL3"; break; deafult: b.var1 = "VAL1-Default"; b.var2 = "VAL2-Default"; b.var3 = "VAL3-Default"; } } </code></pre> <p>I've tired a series of if/then statements and case statements with if/then statements</p> <pre><code>if (b.event_name === "form_completion" &amp;&amp; b['dom.url'].indexOf("Req-Quote-Thanks-Modal") &gt; -1) { b.var1 = "VAL1"; b.var2 = "VAL2"; b.var3 = "VAL3"; } else if (b.event_name === "form_completion" &amp;&amp; b['dom.pathname'].indexOf("sweeps-thank-you") &gt;-1) { b.var1 = "VAL1"; b.var2 = "VAL2"; b.var3 = "VAL4"; } else if (b.event_name === "form_completion" &amp;&amp; b['dom.pathname'].indexOf("special-offers-thank-you") &gt;-1) { b.var1 = "VAL1"; b.var2 = "VAL2"; b.var3 = "VAL5"; } else if (b.event_name === "form_completion" &amp;&amp; b['dom.pathname'].indexOf("brochure") &gt;-1 &amp;&amp; b['dom.pathname'].indexOf("thank-you") &gt;-1) { b.var1 = "VAL1"; b.var2 = "VAL2"; b.var3 = "VAL6"; } </code></pre>
0debug
to check a string is palindrome or not : >class palindrome >{ > public static void main(String args[]) > { > String s1=new String(); > Scanner sc= new Scanner(System.in); > System.out.println("Enter the string:"); > s1=sc.nextLine(); > StringBuffer s2=new StringBuffer(s1); > s2.reverse().toString(); > if(s1.equals(s2.toString())) > System.out.println("Given String is palindrome"); else System.out.println("Given String is not palindrome"); } } this is my program code to check whether a string is palindrome or not . i get correct output using this code but i have 2 confusion [1] why cannot we use toString like s1.toString() [2]if i write if(s1.equals(s2)) simply than if condition is skipped and directly else condition is runned in output why so?
0debug
connection.query('SELECT * FROM users WHERE username = ' + input_string)
1threat
change mobile number prefix i.e. +92 to 0 : I am reading calllog record.I read numbers in format like `0333XXXXXXX` and `+92333XXXXXXX`. how can i convert the number +92 to 0 any idea
0debug
Why does const work in some for-loops in JavaScript? : <p>I <strong>do know</strong> why <code>const</code> doesn't work in for-loops. We need to create a new scope and copy over a value into that. So this won't fly.</p> <pre><code>for(const i = 0; i &lt; 5; i++) console.log(i); </code></pre> <p>Whereas this will.</p> <pre><code>for(let i = 0; i &lt; 5; i++) console.log(i); </code></pre> <p>However, I noticed that both of them work when looping though the properties of an object like this.</p> <pre><code>for(let property in thingy) console.log(property); for(const property in thingy) console.log(property); </code></pre> <p>I'm not sure why.</p>
0debug
What does this smiley mean? : My friend texted me `_=_=>_(_);_(_)` and told me that if I can figure out what it meant then I am a very smart person. He told me that it's written in a language called javascript and that if I need any help then I can ask a question on this website. I have no idea what this means. What does this smiley mean?
0debug
static void finish_write_pci_config(sPAPREnvironment *spapr, uint64_t buid, uint32_t addr, uint32_t size, uint32_t val, target_ulong rets) { PCIDevice *pci_dev; if ((size != 1) && (size != 2) && (size != 4)) { rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } pci_dev = find_dev(spapr, buid, addr); addr = rtas_pci_cfgaddr(addr); if (!pci_dev || (addr % size) || (addr >= pci_config_size(pci_dev))) { rtas_st(rets, 0, RTAS_OUT_HW_ERROR); return; } pci_host_config_write_common(pci_dev, addr, pci_config_size(pci_dev), val, size); rtas_st(rets, 0, RTAS_OUT_SUCCESS); }
1threat
void OPPROTO op_addw_ESI_T0(void) { ESI = (ESI & ~0xffff) | ((ESI + T0) & 0xffff); }
1threat
static void decode_scaling_list(GetBitContext *gb, uint8_t *factors, int size, const uint8_t *jvt_list, const uint8_t *fallback_list) { int i, last = 8, next = 8; const uint8_t *scan = size == 16 ? ff_zigzag_scan : ff_zigzag_direct; if (!get_bits1(gb)) memcpy(factors, fallback_list, size * sizeof(uint8_t)); else for (i = 0; i < size; i++) { if (next) next = (last + get_se_golomb(gb)) & 0xff; if (!i && !next) { memcpy(factors, jvt_list, size * sizeof(uint8_t)); break; } last = factors[scan[i]] = next ? next : last; } }
1threat
SQL. How to check if record exists in Table : <p>I have a table "Table1" in database "TestDB". In the table there are 3 columns: id, name, description. So how can I check if record exists in Table1 ?</p>
0debug
qemu_irq xics_assign_irq(struct icp_state *icp, int irq, enum xics_irq_type type) { if ((irq < icp->ics->offset) || (irq >= (icp->ics->offset + icp->ics->nr_irqs))) { return NULL; } assert((type == XICS_MSI) || (type == XICS_LSI)); icp->ics->irqs[irq - icp->ics->offset].type = type; return icp->ics->qirqs[irq - icp->ics->offset]; }
1threat
def get_noOfways(n): if (n == 0): return 0; if (n == 1): return 1; return get_noOfways(n - 1) + get_noOfways(n - 2);
0debug
int qemu_savevm_state_iterate(QEMUFile *f) { SaveStateEntry *se; int ret = 1; trace_savevm_state_iterate(); QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { if (!se->ops || !se->ops->save_live_iterate) { continue; } if (se->ops && se->ops->is_active) { if (!se->ops->is_active(se->opaque)) { continue; } } if (qemu_file_rate_limit(f)) { return 0; } trace_savevm_section_start(se->idstr, se->section_id); save_section_header(f, se, QEMU_VM_SECTION_PART); ret = se->ops->save_live_iterate(f, se->opaque); trace_savevm_section_end(se->idstr, se->section_id, ret); if (ret < 0) { qemu_file_set_error(f, ret); } if (ret <= 0) { break; } } return ret; }
1threat
How to SET the number of lines for a UILabel using Swift in Xcode : I am currently working on a project where I need to be able to set the number of lines for a UILabel. This means that if I input 5, the label HAS to conform and return 4 times (issues like having too few characters will not be a problem). So far, I have tried to do this by setting the .numberOfRows property, but this only places a limit on the UILabel which is not what I desire (if you are curious, there is some code below). Any help? My code: if Double(w!) > 277 { print("Values:") print(w!) let numRows = Int(w!/237) print(numRows) heightOfCell += Double(numRows)*20.5 cell!.textLabel?.numberOfLines = numRows + 2 }
0debug
people.connections.list not returning contacts using Python Client Library : <p>I'm trying to programmatically access the list of contacts on my own personal Google Account using the Python Client Library</p> <p>This is a script that will run on a server without user input, so I have it set up to use credentials from a Service Account I set up. My Google API console setup looks like this. </p> <p><a href="https://i.stack.imgur.com/bTX2H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bTX2H.png" alt="enter image description here"></a></p> <p>I'm using the following basic script, pulled from the examples provided in the API docs -</p> <pre><code>import json from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build # Only need read-only access scopes = ['https://www.googleapis.com/auth/contacts.readonly'] # JSON file downloaded from Google API Console when creating the service account credentials = ServiceAccountCredentials.from_json_keyfile_name( 'keep-in-touch-5d3ebc885d4c.json', scopes) # Build the API Service service = build('people', 'v1', credentials=credentials) # Query for the results results = service.people().connections().list(resourceName='people/me').execute() # The result set is a dictionary and should contain the key 'connections' connections = results.get('connections', []) print connections #=&gt; [] - empty! </code></pre> <p>When I hit the API it returns a result set without any 'connections' key. Specifically it returns -</p> <pre><code>&gt;&gt;&gt; results {u'nextSyncToken': u'CNP66PXjKhIBMRj-EioECAAQAQ'} </code></pre> <p>Is there something pertaining to my setup or code that's incorrect? Is there a way to see the response HTTP status code or get any further detail about what it's trying to do?</p> <p>Thanks!</p> <p>Side note: When I try it using <a href="https://developers.google.com/people/api/rest/v1/people.connections/list#try-it" rel="noreferrer">the "Try it!" feature in the API docs</a>, it correctly returns my contacts. Although I doubt that uses the client library and instead relies on user authorization via OAuth</p>
0debug
static void pci_get_node_name(char *nodename, int len, PCIDevice *dev) { int slot = PCI_SLOT(dev->devfn); int func = PCI_FUNC(dev->devfn); uint32_t ccode = pci_default_read_config(dev, PCI_CLASS_PROG, 3); const char *name; name = pci_find_device_name((ccode >> 16) & 0xff, (ccode >> 8) & 0xff, ccode & 0xff); if (func != 0) { snprintf(nodename, len, "%s@%x,%x", name, slot, func); } else { snprintf(nodename, len, "%s@%x", name, slot); } }
1threat
Cannot uninstall angular-cli : <p>I've tried several times to uninstall my angular-cli in order to update it but even if I follow the instructions provided on github:</p> <ul> <li>npm uninstall -g @angular/cli</li> <li>npm cache clean</li> <li>npm install -g @angular/cli@latest</li> </ul> <p>When I check using the command ng --version I still get the old version :</p> <pre><code> angular-cli: 1.0.0-beta.26 node: 7.7.1 os: darwin x64 </code></pre> <p>How can i fix this issue? Thanks</p>
0debug
C Program to get the version of jar file : <p>A c program code to get the file version of jar file and we need to compare with some versions and show to the user , we know that it is easy in java but we wanted in c language only</p>
0debug
static void lm32_cpu_class_init(ObjectClass *oc, void *data) { LM32CPUClass *lcc = LM32_CPU_CLASS(oc); CPUClass *cc = CPU_CLASS(oc); DeviceClass *dc = DEVICE_CLASS(oc); lcc->parent_realize = dc->realize; dc->realize = lm32_cpu_realizefn; lcc->parent_reset = cc->reset; cc->reset = lm32_cpu_reset; cc->class_by_name = lm32_cpu_class_by_name; cc->has_work = lm32_cpu_has_work; cc->do_interrupt = lm32_cpu_do_interrupt; cc->cpu_exec_interrupt = lm32_cpu_exec_interrupt; cc->dump_state = lm32_cpu_dump_state; cc->set_pc = lm32_cpu_set_pc; cc->gdb_read_register = lm32_cpu_gdb_read_register; cc->gdb_write_register = lm32_cpu_gdb_write_register; #ifdef CONFIG_USER_ONLY cc->handle_mmu_fault = lm32_cpu_handle_mmu_fault; #else cc->get_phys_page_debug = lm32_cpu_get_phys_page_debug; cc->vmsd = &vmstate_lm32_cpu; #endif cc->gdb_num_core_regs = 32 + 7; cc->gdb_stop_before_watchpoint = true; cc->debug_excp_handler = lm32_debug_excp_handler; }
1threat
uint64_t HELPER(diag)(CPUS390XState *env, uint32_t num, uint64_t mem, uint64_t code) { uint64_t r; switch (num) { case 0x500: r = s390_virtio_hypercall(env); break; case 0x44: r = 0; break; case 0x308: r = 0; break; default: r = -1; break; } if (r) { program_interrupt(env, PGM_OPERATION, ILEN_LATER_INC); } return r; }
1threat
Git commit lost after merge : <p>We have 3 branches (A, B, C) as below:</p> <pre><code>---\--A1--\------Am------Merge1---An---Merge2--- \ \ / / \ \--C1---C2---/ / \ / \--B1--------------Bn---------/ </code></pre> <p>The problem appears at Merge2. Some commit on branch C ( <strong>not all but some</strong>, let's say C2) is lost on branch A after Merge2, which is present between Merge1 and Merge2.</p> <p>When doing Merge2, there is only one file conflict, which not relates to the lost commit (C2). And we resolve the confilict and finish the merge successfully.</p> <p><strong>It seems like C2 is reversed by Merge2 on branch A, without any log.</strong></p> <p>What happened? What might be the cause to this situation?</p>
0debug
Rebase remote branch onto master while keeping the remote branch updated : <p>I am trying to rebase my remote branch onto master, but I want to keep the remote branch pointing to it's commits, just based at a different point in master.</p> <p>Here is my structure:</p> <pre><code>A - B - C - D (origin/master) \ R - S - T (origin/develop) </code></pre> <p>I would like:</p> <pre><code>A - B - C - D (origin/master) - R - S - T (origin/develop) </code></pre> <p>Is such a rebase possible without some sort of merge?</p>
0debug
error: ‘Board::Board’ names the constructor, not the type Board::Board; C++ : <p>All right so here is the code where the error is,</p> <p>Board::Board {</p> <p>}</p> <p>so, what makes this not compile? </p>
0debug
static void alpha_cpu_initfn(Object *obj) { CPUState *cs = CPU(obj); AlphaCPU *cpu = ALPHA_CPU(obj); CPUAlphaState *env = &cpu->env; cs->env_ptr = env; cpu_exec_init(cs, &error_abort); tlb_flush(cs, 1); alpha_translate_init(); #if defined(CONFIG_USER_ONLY) env->ps = PS_USER_MODE; cpu_alpha_store_fpcr(env, (FPCR_INVD | FPCR_DZED | FPCR_OVFD | FPCR_UNFD | FPCR_INED | FPCR_DNOD | FPCR_DYN_NORMAL)); #endif env->lock_addr = -1; env->fen = 1; }
1threat
React Native: 2 scroll views with 2 sticky headers : <p>I am trying to create a day-view with times on the left side, and a top header of people. Currently I can get the left OR the top header to stick, but not both.</p> <p><strong>How do you get 2 sticky headers?</strong></p> <p><a href="https://i.stack.imgur.com/07CUw.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/07CUw.gif" alt="Two Scroll Views each with a header"></a></p> <p>My render looks like this:</p> <pre><code> &lt;ScrollView style={{height: 600}}&gt; &lt;ScrollView horizontal={true}&gt; &lt;View style={styles.column}&gt; &lt;View style={{ flex: 1, flexDirection: 'row', width}}&gt; {header} &lt;/View&gt; &lt;View style={styles.row}&gt; &lt;View style={[styles.container, { width, marginLeft: 40 }]}&gt; {this.generateRows()} &lt;/View&gt; &lt;/View&gt; &lt;/View&gt; &lt;/ScrollView&gt; &lt;View style={{backgroundColor: 'white', position: 'absolute', top: 0, bottom: 0, left: 0, }}&gt; &lt;View style={{ flex: 1, flexDirection: 'row'}}&gt; &lt;View style={styles.row}&gt; &lt;Text&gt;&lt;/Text&gt; &lt;/View&gt; &lt;/View&gt; &lt;View style={{height: 1000, width: 40 }}&gt; {this.generateRowLabels()} &lt;/View&gt; &lt;/View&gt; &lt;/ScrollView&gt; </code></pre>
0debug
static int dnxhd_encode_picture(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data) { DNXHDEncContext *ctx = avctx->priv_data; int first_field = 1; int offset, i, ret; if (buf_size < ctx->cid_table->frame_size) { av_log(avctx, AV_LOG_ERROR, "output buffer is too small to compress picture\n"); return -1; } dnxhd_load_picture(ctx, data); encode_coding_unit: for (i = 0; i < 3; i++) { ctx->src[i] = ctx->frame.data[i]; if (ctx->interlaced && ctx->cur_field) ctx->src[i] += ctx->frame.linesize[i]; } dnxhd_write_header(avctx, buf); if (avctx->mb_decision == FF_MB_DECISION_RD) ret = dnxhd_encode_rdo(avctx, ctx); else ret = dnxhd_encode_fast(avctx, ctx); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "picture could not fit ratecontrol constraints\n"); return -1; } dnxhd_setup_threads_slices(ctx, buf); offset = 0; for (i = 0; i < ctx->m.mb_height; i++) { AV_WB32(ctx->msip + i * 4, offset); offset += ctx->slice_size[i]; assert(!(ctx->slice_size[i] & 3)); } avctx->execute(avctx, dnxhd_encode_thread, (void**)&ctx->thread[0], NULL, avctx->thread_count, sizeof(void*)); AV_WB32(buf + ctx->cid_table->coding_unit_size - 4, 0x600DC0DE); if (ctx->interlaced && first_field) { first_field = 0; ctx->cur_field ^= 1; buf += ctx->cid_table->coding_unit_size; buf_size -= ctx->cid_table->coding_unit_size; goto encode_coding_unit; } ctx->frame.quality = ctx->qscale*FF_QP2LAMBDA; return ctx->cid_table->frame_size; }
1threat
Why aren't Facebook using svgs for their icons? : <p>Why are Facebook using really shitty pngs for their icons? They look like crap.</p> <p>Is it because of browser compability? Speed? Browser performance?</p>
0debug
void virtio_bus_device_plugged(VirtIODevice *vdev, Error **errp) { DeviceState *qdev = DEVICE(vdev); BusState *qbus = BUS(qdev_get_parent_bus(qdev)); VirtioBusState *bus = VIRTIO_BUS(qbus); VirtioBusClass *klass = VIRTIO_BUS_GET_CLASS(bus); VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev); bool has_iommu = virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM); DPRINTF("%s: plug device.\n", qbus->name); if (klass->pre_plugged != NULL) { klass->pre_plugged(qbus->parent, errp); } assert(vdc->get_features != NULL); vdev->host_features = vdc->get_features(vdev, vdev->host_features, errp); if (klass->device_plugged != NULL) { klass->device_plugged(qbus->parent, errp); } if (klass->get_dma_as != NULL && has_iommu) { virtio_add_feature(&vdev->host_features, VIRTIO_F_IOMMU_PLATFORM); vdev->dma_as = klass->get_dma_as(qbus->parent); } else { vdev->dma_as = &address_space_memory; } }
1threat
static int decode_value(SCPRContext *s, unsigned *cnt, unsigned maxc, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = cnt[maxc]; unsigned value; unsigned c = 0, cumfr = 0, cnt_c = 0; int i, ret; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (c < maxc) { cnt_c = cnt[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } s->decode(gb, rc, cumfr, cnt_c, totfr); cnt[c] = cnt_c + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < maxc; i++) { unsigned nc = (cnt[i] >> 1) + 1; cnt[i] = nc; totfr += nc; } } cnt[maxc] = totfr; *rval = c; return 0; }
1threat
How to get webDriver to wait for page to load (C# Selenium project) : <p>I've started a Selenium project in C#. Trying to wait for page to finish loading up and only afterwards proceed to next action.</p> <p>My code looks like this:</p> <pre><code> loginPage.GoToLoginPage(); loginPage.LoginAs(TestCase.Username, TestCase.Password); loginPage.SelectRole(TestCase.Orgunit); loginPage.AcceptRole(); </code></pre> <p>inside loginPage.SelectRole(TestCase.Orgunit):</p> <pre><code> RoleHierachyLabel = CommonsBasePage.Driver.FindElement(By.XPath("//span[contains(text(), " + role + ")]")); RoleHierachyLabel.Click(); RoleLoginButton.Click(); </code></pre> <p>I search for element RoleHierachyLabel. I've been trying to use multiple ways to wait for page to load or search for an element property allowing for some timeout:</p> <pre><code>1. _browserInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); </code></pre> <hr> <pre><code>2. public static bool WaitUntilElementIsPresent(RemoteWebDriver driver, By by, int timeout = 5) { for (var i = 0; i &lt; timeout; i++) { if (driver.ElementExists(by)) return true; } return false; } </code></pre> <p>How would you tackle this obstacle?</p>
0debug
Pass swift variables to JavaScript : My problem is that I want to pass TWO variables from xcode to javascript to the same method but it won't work I didn't get the reason the statement is webView.evaluateJavaScript("saveData(\(userID, username))", completionHandler: nil) Where the variables is userID and user name THANKS
0debug
Content Margin Depend on Other Div : I have created 2 div next to each other(Left and Right)the height depend on each other I just use display: table-cell for it. But on the left div if any item has margin it is affect right div content, content going down while I increase the margin how to solve it ? Thank you.
0debug
Can we know the fingerprint id of touched fingerprint on Android : I have 5 fingerprints on my phone. Can I detect which finger's fingerprint is touched when the user touch with any of the fingerprints on the device. I tried this with `FingerprintManager` but I failed. Please let me know is this even possible.
0debug
PPC_OP(clear_xer_cr) { xer_so = 0; xer_ov = 0; xer_ca = 0; RETURN(); }
1threat