input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Finding first n primes efficiently <p>I have a brute-force algorithm that takes an input n, and displays the first n prime numbers. The code works, but I also have to answer this question:</p>
<blockquote>
<p>Give the number of test items that would be required to assure correctness.</p>
</blockquote>
<p>Is there a way to calculate this? Would I technically need to test every possible int value (all 2 billion possibilities)?</p>
| <p>If you have a number <em>n</em>, and need to check if it is a prime, there are more efficient ways than brute force.</p>
<p>One way would be to use the <a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test" rel="nofollow">Miller-Rabin Primality Test</a>. The Miller-Rabin test either finds proof that a number is a composite, or it does not such find proof (it does not directly prove that a number is a prime). So the scheme would be:</p>
<ol>
<li><p>run Miller-Rabin at most <em>k</em> times (or until it found that the number is a composite)</p></li>
<li><p>if Miller-Rabin claims it is a possible prime, perform a brute force check</p></li>
</ol>
<p>Miller-Rabin runs <a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Concepts" rel="nofollow">as follows</a>. Obviously, you need test only for odd <em>n</em>, and so <em>n - 1</em> is even, and you can write <em>n - 1 = 2<sup>s</sup>d</em> for some positive <em>s</em> and positive odd <em>d</em>. Randomly choose an <em>a</em> from the range <em>(0, n - 1)</em>. If <em>a<sup>d</sup> ≠ 1 | n</em> and <em>a<sup>2<sup>r</sup>d</sup> ≠ -1 | n</em>, then <em>n</em> is a composite. </p>
<p>If <em>n</em> is a composite, the probability that <em>k</em> iterations of Miller-Rabin will not prove it so, is less than <em>4<sup>-k</sup></em>. Note that by the <a href="https://en.wikipedia.org/wiki/Prime_number_theorem" rel="nofollow">Prime Number theorem</a>, primes are scarce.</p>
<p>The computational-complexity of <em>k</em> applications of Miller-Rabin, even with a naive implementation, <a href="https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Computational_complexity" rel="nofollow">is</a>, is <em>O(k log<sup>3</sup>(n))</em>.</p>
|
Query with linq using a where clause <p>Okay so I've already asked this question but I've narrowed it down and am now able to word it better.</p>
<p>I have a sql database and an asp.net mvc project with entity frameworks. I already figured out how to query the database and display all contents. But now I need to query the database and only display the rows where column "a" is greater than or equal to column "b".</p>
<p>Edit: datatypes in both columns are int</p>
<p>Here is the query I need</p>
<pre><code>Select *
from Inventory
Where quantity <= statusLow
</code></pre>
| <pre><code>var context = new MyContext();
var query = context.Inventory.Where(p=> p.quantity <= p.statusLow); // write the statement to query
var result = query.ToList(); // obtaining the result, trigger the database
</code></pre>
|
Dynamic templateURL with Angular 2 version of the Angular UI Bootstrap library <p>I am creating a dynamic template URL using the following code <a href="http://stackoverflow.com/questions/39410355/how-to-use-variable-to-define-templateurl-in-angular2#answer-39411464">How to use variable to define templateUrl in Angular2</a>, but I need to use a datepicker in the template and I had problems to add the Angular UI Bootstrap library (Angular 2 version). The error is </p>
<p><em>"No provider for NgbDateParserFormatter"</em></p>
<p>I added NgbModule and FormsModule to the section imports</p>
<pre><code>@NgModule({
imports: [CommonModule, NgbModule.forRoot(), FormsModule ],
declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule {}
</code></pre>
<p>I created a plunker version <a href="https://plnkr.co/edit/kWoSTi?p=preview" rel="nofollow">https://plnkr.co/edit/kWoSTi?p=preview</a>
If the field date in the file <code>src/articles/first.html</code> is uncommented the application doesn´t work.</p>
| <p>I would leverage the following way to do it working :</p>
<pre><code>this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then(factory => {
const moduleRef = factory.ngModuleFactory.create(this.vcRef.parentInjector);
const compFactory = factory.componentFactories
.find(x => x.componentType === DynamicHtmlComponent);
const cmpRef = this.vcRef.createComponent(compFactory, 0, moduleRef.injector);
});
</code></pre>
<p><strong><a href="https://plnkr.co/edit/MnYtBi?p=preview" rel="nofollow">Plunker Example</a></strong></p>
<blockquote>
<p>One note: you can use <code>NgbDatepickerModule</code> instead of <code>NgbModule</code>. It
will improve performance <strong><a href="https://plnkr.co/edit/7n4oz2?p=preview" rel="nofollow">Plunker</a></strong></p>
</blockquote>
|
How to use one class in jquery to php/html foreach loop? <p>My title is quite confusing but my question is..</p>
<p>is have this script plugin wherein the plugin will create a bubble-like progress bar found <a href="http://www.jqueryscript.net/chart-graph/Customizable-Liquid-Bubble-Chart-With-jQuery-Canvas.html" rel="nofollow">here</a>.</p>
<p>in the script I have <code>$('.demo').waterbubble();</code></p>
<p>now have a foreach loop that is.. </p>
<pre><code><?php foreach($bins as $binArray): ?>
<div class="row">
<?php foreach ($binArray as $bin):?>
<div class="col-xs-8">
<canvas class="demo"></canvas>
</div>
<?php endforeach;?>
</div>
<?php endforeach; ?>
</code></pre>
<p>so in this code it should iterate the canvas and display bubbles depending on the <code>$bin</code> variable. I tested with 6 iterations so it should show 6 bubbles, but instead it only shows one bubble and the others are not showing any bubbles. I inspect the code and the <code><canvas class="demo"></canvas></code> is iterated properly but not showing anything for some reason. Any one knows why is that? and is there any way to use this or to work around this? thank you very much!</p>
| <p>I'm guessing it's an issue with the script. You might be better off trying to init each waterbubble with a unique ID.</p>
<pre><code><?php foreach($bins as $binArray): ?>
<div class="row">
<?php foreach ($binArray as $bin):?>
<div class="col-xs-8">
<canvas id="demo<?= $bin[number] ?>"></canvas>
</div>
<script>
$('#demo<?= $bin[number] ?>').waterbubble();
</script>
<?php endforeach;?>
</div>
<?php endforeach; ?>
</code></pre>
|
Remote command does not return python <p>I am rebooting a remote machine through Python, as it is a reboot, the current ssh session is killed. The request is not returned. I am not interested in the return though.</p>
<p>os.command('sshpass -p password ssh user@host reboot')</p>
<p>The code is performing the reboot, however the current session is killed and the script never returns.</p>
<p>I can do an async and just ignore the thread, any other easy options?</p>
| <p>I'm surprised that the script doesn't return. The connection should be reset by the remote before it reboots. You can run the process asyc, the one problem is that subprocesses not cleaned up up by their parents become zombies (still take up space in the process table). You can add a Timer to give the script time to do its dirty work and then clean it up in the background.</p>
<p>Notice that I switched that command to a list of parameters and skipped setting <code>shell=True</code>. It just means that no intermediate shell process is executed.</p>
<pre><code>import sys
import subprocess as subp
import threading
import timing
def kill_process(proc):
# kill process if alive
if proc.poll() is None:
proc.kill()
time.sleep(.1)
if proc.poll() is None:
sys.stderr.write("Proc won't die\n")
return
# clean up dead process
proc.wait()
proc = subp.Popen(['sshpass', '-p', password, 'ssh', 'user@host', 'reboot')
threading.Timer(5, kill_process, args=(proc,))
# continue on your busy day...
</code></pre>
|
Evernote Initial Sync Boost <p>I'm working on an application that requires completely syncing a users Evernote account, however on some larger account we run into rate limits. According to the API documentation there is a feature known as Initial Sync Boost, however I can not find any information on how to implement this other than - </p>
<blockquote>
<p>"You may request this when your key is created or when you are
activating your API key in our production environment"</p>
</blockquote>
<p>When looking at creating a token sync boost is not listed as one of the parameters.</p>
<p>Can anyone clarify this ? </p>
| <p>You don't have to implement anything on your side. When you activate your key on the production environment on <a href="https://dev.evernote.com/support/" rel="nofollow">this page</a>, you can request the initial sync boost so the support increase the limit for the initial sync for your key.</p>
|
Optimizing HTTP request and multiple Split on CSV file <p>I'm trying to read a CSV file from a website, then split the initial string by <code>\n</code>, then split again by <code>,</code>.
When I try to print out the content of one of the arrays, it was very slow, it takes almost one second between each <code>Console.WriteLine()</code> that prints each element.</p>
<p>I'm not entirely sure why it takes such great deal of time to print.</p>
<p>Any pointers will help</p>
<pre><code>public List<string[]> list = new List<string[]>();
public List<string[]> Content
{
get
{
using (var url = new WebClient())
{
_content = url.DownloadString("https://docs.google.com/spreadsheets/d/1DDhAd98p5RwXqvV53P2YvaujIQEg28HjeXasrCge9Qo/pub?output=csv");
}
var urlArr = _content.Split('\n');
foreach (var i in urlArr)
{
var contentArr = i.Split(',');
List.Add(contentArr);
}
return list;
}
}
</code></pre>
<p>Main</p>
<pre><code> var data = new ReadCSV();
for(var i = 0; i < data.Content[2].Length; i++)
Console.WriteLine(data.Content[2][i]);
</code></pre>
| <p>You should cache the results in a variable, either in the <code>Content</code> property or before the loop because currently your code downloads and split the string every time in the loop which is why it is taking 1 second</p>
<p>So, your code should look like this:</p>
<pre><code>var data = new ReadCSV();
var content = data.Content[2];
for(var i = 0; i < content.Length; i++)
Console.WriteLine(content[2][i]);
</code></pre>
|
How do I printout multiple text in JText Field using if/else statement? <p><a href="https://i.stack.imgur.com/DhyT8.png" rel="nofollow"><img src="https://i.stack.imgur.com/DhyT8.png" alt=""></a></p>
<pre><code> private void resultActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(pick1 > pick2 ){
resultstf.setText("The New President is Koon!");
}
else if(pick2 > pick1){
resultstf.setText("The New President is Baam!");
}
else if(pick1 == pick2){
resultstf.setText("The Result for the new President is a Tie! Please Vote Again.");
}
if(pick3 > pick4){
resultstf.setText("The New VP is Sachi!");
}
else if(pick4 > pick3){
resultstf.setText("The New VP is Faker!");
}
}
</code></pre>
<p>How do I print out multiple Text whenever I press the Result Button? Like I want to print out "The New President is Koon" and also printout "The New VP is Sachi" at the same time.</p>
| <p>Use a <code>StringBuilder</code> and build the message as you go along:</p>
<pre><code>private void resultActionPerformed(java.awt.event.ActionEvent evt) {
StringBuilder message = new StringBuilder();
// TODO add your handling code here:
if (pick1 > pick2) {
message.append("The New President is Koon!\n");
}
else if (pick2 > pick1) {
message.append("The New President is Baam!\n");
}
else if (pick1 == pick2) {
message.append("The Result for the new President is a Tie! Please Vote Again.\n");
}
if (pick3 > pick4) {
message.append("The New VP is Sachi!\n");
}
else if (pick4 > pick3) {
message.append("The New VP is Faker!\n");
}
resultstf.setText(message.toString());
}
</code></pre>
|
code working good in chrome, firefox, mircrosoft edge but not working in safari <p>I am creating a website for my client. Website is working great in Chrome, Firefox, Microsoft Edge and Even Internet Explorer :P. But I don't know why this site is not working in Safari. This is my code:-
HTML </p>
<pre><code><html>
<head>
<title>Welcome to Siyaram Developers</title>
</head>
<body>
<div id="overlay"></div>
<div id="background"></div>
<div id="mainContainer">
<div id="logo"><img src="#" width="150px" height="50px" alt="siyaram developers"/></div>
<div id="navlinks">
<div id="menuContainer">
<a href="#" onclick="showContent('home')">Home</a>
<a href="#" onclick="showContent('about-us')">About-Us</a>
<a href="#;" onclick="showContent('projects')">Our Projects</a>
<a href="#" onclick="showContent('vision')">Vision</a>
<a href="#contactForm" onclick="showContent('contactForm')">Contact-Us</a>
<a href="#login" onclick="showContent('login')">Members</a>
</div>
</div>
<div id="middle">
<div id="home">
Welcome to the Siyaram Developers.
</div>
<div id="about-us">
<h3>About Us</h3>
<p style="float: left;">
<img src="img/a.jpg" width="250px" height="250px" alt="Sunny Bhadana" title="Sunny Bhadana"/>
</p>
<p>
<script>
for(i=0; i<10; i++){
document.write("This is Some Dummy Text. This text is just for testing this site. And it's working Great.");
}
</script>
</p> </div>
<div id="vision">
<img src="img/vision.jpg" width="100%" height="auto" alt="Vision" title="Vision">
<h3>Vision</h3>
<p>Our vision is to deliver positive, engaging and memorable experiences to our patrons and partners and
continuously strive for innovation in product design and processes with integrity and transparency.</p> </div>
<div id="projects">
<img src="img/company.jpg" width="100%" height="auto" alt="Project" title="Project">
<h3>Our Projects</h3>
<p>Our Project list here;---</p> </div>
<div id="contactForm">
<img src="img/contact.jpg" width="100%" alt="Contact-Us">
<h3>Contact-Us</h3>
<br />
<b>Notice</b>: Undefined variable: status in <b>C:\xampp\htdocs\siyaramdevelopers\includes\contact.php</b> on line <b>3</b><br />
<form name="contact-form" action="index.php" method="post" onsubmit="validate()">
<input type="text" name="name" placeholder="Your Name"/><br/>
<input type="number" name="number" placeholder="Your Mobile Number"/><br/>
<input type="email" name="email" placeholder="Your E-mail Address"/><br/>
<textarea name="message" placeholder="Your Suggestion/Questions" cols="10" rows="5"></textarea><br/>
<input type="submit" value="Submit">
</form> </div>
<div id="login">
<table width="100%">
<tr>
<td width="32%"><input type="button" id="log_in" onclick="show('log_in')" value="Log-In"/></td>
<td width="32%"><input type="button" onclick="show('sign_up')" id="sign_up" value="Sign-Up"/></td>
<td width="32%"><input type="button" onclick="show('admin_login')" id="admin_login" value="Admin Login"/></td>
</tr>
<tr>
<td valign="top" align="center">
<form name="loginForm" onsubmit="return false;">
<input type="email" id="login_username" placeholder="Email Address"><br/>
<input type="password" id="login_password" placeholder="Password"><br/>
<input type="button" onclick="validateData()" value="Login"><br/>
<a href="#">Forgot Password?</a>
<br/>
</form>
</td>
<td valign="top" align="center">
<form name="signupForm" onsubmit="return false">
<input type="text" id="sign_name" placeholder="Your Name"/><br/>
<input type="email" id="sign_email" placeholder="Your Email"/><br/>
<input type="password" id="sign_password" placeholder="Password"/><br/>
<input type="number" id="sign_mobile" placeholder="Mobile Number"/><br/>
<input type="button" onclick="userSignUp()" value="Sign-Up" /><br/>
</form>
</td>
<td valign="top" align="center">
<form name="admin_login" onsubmit="return false">
<input type="email" id="admin_username" placeholder="Email Address"><br/>
<input type="password" id="admin_password" placeholder="Password"><br/>
<input type="button" onclick="login_admin()" value="Login"><br/>
<br/>
</form>
</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>Java Script Code</strong></p>
<pre><code><script>
function validateData() {
var username = document.getElementById("login_username").value;
var password = document.getElementById("login_password").value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "login_test.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "login_undone"){
alert("Login Failed");
}else {
window.location.assign("user.php?username="+ajax.responseText);
}
}
}
ajax.send("username="+username+"&password="+password);
}
function login_admin() {
var admin_username = document.getElementById("admin_username").value;
var admin_password = document.getElementById("admin_password").value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "login_test.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "login_done") {
window.location.assign('admin/index.php');
}else {
alert('Sorry! Wrong Creditionals');
}
}
}
ajax.send("admin_username="+admin_username+"&admin_password="+admin_password);
}
function userSignUp() {
var username = document.getElementById("sign_name").value;
var password = document.getElementById("sign_password").value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "login_test.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
alert(ajax.responseText);
}
}
ajax.send("signup_username="+username+"&signup_password="+password);
}
function showContent(conId){
var current = document.getElementById(conId);
if(current == document.getElementById("about-us")) {
//hide if any links are opened
document.getElementById("vision").style.position = "fixed";
document.getElementById("projects").style.position = "fixed";
document.getElementById("contactForm").style.position = "fixed";
document.getElementById("login").style.position = "fixed";
document.getElementById("home").style.position = "fixed";
document.getElementById("home").style.left = "100%";
document.getElementById("login").style.left = "100%";
document.getElementById("contactForm").style.left = "100%";
document.getElementById("vision").style.left = "100%";
document.getElementById("projects").style.left = "100%";
document.getElementById("projects").style.transition = "0.5s";
document.getElementById("vision").style.transition = "0.5s";
document.getElementById("contactForm").style.transition = "0.5s";
document.getElementById("login").style.transition = "0.5s";
document.getElementById("home").style.transition = "0.5s";
//show the current link which user clicks
current.style.position = "absolute";
current.style.left = "0";
current.style.transition = "left 1s";
// current.style.right = "50px";
}else if(current == document.getElementById("vision")){
//change absolute to fixed position
document.getElementById("about-us").style.position = "fixed";
document.getElementById("projects").style.position = "fixed";
document.getElementById("contactForm").style.position = "fixed";
document.getElementById("login").style.position = "fixed";
document.getElementById("home").style.position = "fixed";
document.getElementById("home").style.left = "100%";
//make left align 100%
document.getElementById("contactForm").style.left = "100%";
document.getElementById("login").style.left = "100%";
document.getElementById("about-us").style.left = "100%";
document.getElementById("projects").style.left = "100%";
//transition 0.5s
document.getElementById("about-us").style.transition = "0.5s";
document.getElementById("projects").style.transition = "0.5s";
document.getElementById("contactForm").style.transition = "0.5s";
document.getElementById("login").style.transition = "0.5s";
document.getElementById("home").style.transition = "0.5s";
current.style.position = "absolute";
current.style.left = "0";
current.style.transition = "left 1s";
// current.style.left = "50px";
}else if(current == document.getElementById("projects")){
document.getElementById("about-us").style.position = "fixed";
document.getElementById("about-us").style.position = "fixed";
document.getElementById("contactForm").style.position = "fixed";
document.getElementById("login").style.position = "fixed";
document.getElementById("home").style.position = "fixed";
document.getElementById("home").style.left = "100%";
document.getElementById("login").style.left = "100%";
document.getElementById("contactForm").style.left = "100%";
document.getElementById("about-us").style.left = "100%";
document.getElementById("vision").style.position = "fixed";
document.getElementById("vision").style.left = "100%";
document.getElementById("vision").style.transition = "0.5s";
document.getElementById("about-us").style.transition = "0.5s";
document.getElementById("contactForm").style.transition = "0.5s";
document.getElementById("login").style.transition = "0.5s";
document.getElementById("home").style.transition = "0.5s";
//show contents
current.style.position = "absolute";
current.style.left = "50";
current.style.transition = "left 1s";
}else if(current == document.getElementById("contactForm")){
document.getElementById("vision").style.position = "fixed";
document.getElementById("projects").style.position = "fixed";
document.getElementById("about-us").style.position = "fixed";
document.getElementById("login").style.position = "fixed";
document.getElementById("home").style.position = "fixed";
document.getElementById("home").style.left = "100%";
document.getElementById("login").style.left = "100%";
document.getElementById("about-us").style.left = "100%";
document.getElementById("vision").style.left = "100%";
document.getElementById("projects").style.left = "100%";
document.getElementById("projects").style.transition = "0.5s";
document.getElementById("about-us").style.transition = "0.5s";
document.getElementById("vision").style.transition = "0.5s";
document.getElementById("login").style.transition = "0.5s";
document.getElementById("home").style.transition = "0.5s";
current.style.position = "absolute";
current.style.left = "0";
current.style.transition = "left 1s";
}else if(current == document.getElementById("login")){
document.getElementById("vision").style.position = "fixed";
document.getElementById("projects").style.position = "fixed";
document.getElementById("about-us").style.position = "fixed";
document.getElementById("contactForm").style.position = "fixed";
document.getElementById("home").style.position = "fixed";
document.getElementById("home").style.left = "100%";
document.getElementById("about-us").style.left = "100%";
document.getElementById("vision").style.left = "100%";
document.getElementById("projects").style.left = "100%";
document.getElementById("contactForm").style.left = "100%";
document.getElementById("projects").style.transition = "0.5s";
document.getElementById("about-us").style.transition = "0.5s";
document.getElementById("vision").style.transition = "0.5s";
document.getElementById("contactForm").style.transition = "0.5s";
document.getElementById("home").style.transition = "0.5s";
current.style.position = "absolute";
current.style.left = "0";
current.style.transition = "left 1s";
}else if(current == document.getElementById("home")){
document.getElementById("vision").style.position = "fixed";
document.getElementById("projects").style.position = "fixed";
document.getElementById("about-us").style.position = "fixed";
document.getElementById("contactForm").style.position = "fixed";
document.getElementById("login").style.position = "fixed";
document.getElementById("login").style.left = "100%";
document.getElementById("about-us").style.left = "100%";
document.getElementById("vision").style.left = "100%";
document.getElementById("projects").style.left = "100%";
document.getElementById("contactForm").style.left = "100%";
document.getElementById("projects").style.transition = "0.5s";
document.getElementById("about-us").style.transition = "0.5s";
document.getElementById("vision").style.transition = "0.5s";
document.getElementById("contactForm").style.transition = "0.5s";
document.getElementById("login").style.transition = "0.5s";
current.style.position = "absolute";
current.style.left = "0";
current.style.transition = "left 1s";
}
}
function show(item) {
if(item == 'admin_login'){
alert('admin');
}
if(item == 'sign_up'){
alert('sign_up');
}
if(item == 'log_in'){
alert('member');
}
}
</script>
</code></pre>
<p><strong>CSS Code</strong></p>
<pre><code><style>
@font-face {
font-family: myFont;
src: url("http://localhost/siyaramdevelopers/fonts/lucida-sans-unicode.woff");
}
body {
font-family: myFont;
background-color: black;
overflow-x: hidden;
}
#background {
position: fixed;
left:0;
top:0;
background: url("http://localhost/siyaramdevelopers/img/background.jpg");
width: 100vw;
height: 100vh;
z-index: 10;
}
#overlay {
position: fixed;
left:0;
top:0;
width: 100vw;
background-color: black;
height: 100vh;
z-index: 20;
opacity: 0.6;
filter:alpha(opacity=60);
}
#mainContainer {
position: absolute;
/*border:1px solid yellow;*/
z-index: 30;
width: 80%;
margin-left: 10%;
margin-right: 10%;
}
#navlinks {
position: fixed;
height: 120px;
width:100vw;
top: 0;
left: 0;
z-index: 40;
background-color: rgba(12, 12, 12, 0.77);
}
#mainContainer > #navlinks > #menuContainer {
width:600px;
/*min-width: 600px;*/
margin-top: 80px;
position: absolute;
right:10px;
/*border:1px solid red;*/
/*left: 50px;*/
}
@media screen and (max-width: 635px) {
body {
overflow-x: auto;
}
#navlinks {
position: absolute;
width: 700px;
}
#mainContainer > #navlinks > #menuContainer {
left:10px;
}
#mainContainer > #navlinks > #menuContainer > a {
margin-bottom: 10px;
}
}
#mainContainer > #navlinks > #menuContainer > a {
text-decoration: none;
border: 2px solid white;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;;
/*float: right;*/
margin: 5px;
padding: 5px;
color: #fff;
margin-top: 70px;
outline: none;
}
#mainContainer > #navlinks > #menuContainer > a:hover {
/*border: 2px solid white;*/
background-color: rgba(28, 77, 233, 0.77);
-webkit-transition: 0.5s;
-moz-transition: 0.5s ;
-ms-transition: 0.5s ;
-o-transition: 0.5s ;
transition: 0.5s ;
}
#logo {
position: fixed;
margin-left: 50px;
width: 150px;
/*border:2px solid blue;*/
}
#middle {
margin-top: 150px;
color: #fff;
}
#about-us, #vision, #projects, #contactForm, #login {
position: fixed;
width: 90%;
/*top: 150px;*/
/*right:100px;*/
left:100%;
}
#middle > #about-us > p > img {
margin-right: 20px;
}
#vision > img, #about-us > img, #contactForm > img, #projects > img {
display: none;
}
/*Contact-us page style*/
h3 {
text-align: center;
}
#admin_login, #sign_up, #log_in {
width:100%;
height:40px;
background: transparent;
border: 2px solid white;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #fff;
outline:none;
font-size: medium;
}
form[name=contact-form], form[name=loginForm], form[name=signupForm], form[name=admin_login]{
/*border: 1px solid red;*/
text-align: center;
}
form[name=contact-form] > input[type=text],
form[name=contact-form] > input[type=number],
form[name=contact-form] > input[type=email],
form[name=loginForm] > input[type=email],
form[name=loginForm] > input[type=password],
form[name=loginForm] > input[type=button],
form[name=signupForm] > input[type=text],
form[name=signupForm] > input[type=email],
form[name=signupForm] > input[type=password],
form[name=signupForm] > input[type=number],
form[name=signupForm] > input[type=button],
form[name=admin_login] > input[type=email],
form[name=admin_login] > input[type=password],
form[name=admin_login] > input[type=button]
{
height: 40px;
width:250px;
margin: 10px;
background: transparent;
border: 2px solid white;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #fff;
outline:none;
font-size: medium;
}
form[name=contact-form] > textarea {
width:250px;
background: transparent;
border:2px solid white;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #fff;
font-size: medium;
outline:none;
margin-bottom: 20px;
resize: none;
}
form[name=contact-form] > input[type=submit] {
width:250px;
height: 40px;
border:2px solid white;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
font-size: medium;
background: transparent;
color: #fff;
outline:none;
}
form[name=loginForm] > a {
text-decoration: none;
color: #fff;
}
#admin_login, #sign_up, #logForm {
border: 2px solid white;
background-color: transparent;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
font-size: medium;
margin-top: 0;
padding: 5px;
color: #fff;
outline: none;
}
form[name=admin_login], form[name=loginForm], form[name=signupForm] {
display: inline;
}
form[name=admin_login] > #username, form[name=loginForm] > #username, form[name=signupForm] > #name {
margin-top: 30px;
}
</style>
</code></pre>
<p>and this is screen-shot of Chrome
<a href="https://i.stack.imgur.com/b5NZd.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/b5NZd.jpg" alt="enter image description here"></a></p>
<p>this is in Safari
<a href="https://i.stack.imgur.com/iCMDF.png" rel="nofollow"><img src="https://i.stack.imgur.com/iCMDF.png" alt="enter image description here"></a> </p>
| <p>Finally I got it :). It takes some time but now I know why my code is not running correctly on Safari. </p>
<p>I have to test my css code one by one by commenting it. Offf.!
But when I comment </p>
<pre><code>width:100vw;
height:100vh;
</code></pre>
<p>I got some result. Then I changed it to </p>
<pre><code>width:100%;
height:100%;
</code></pre>
<p>And it works!
Now, I don't know that vh or vw is supported or not in Safari because when I used % in place of vh and vw my code run Correctly. </p>
|
IOS: Move TextField Up When Keyboard Appears <p>I am using the following method to move the view upwards when the keyboard appears so the keyboard does not block a textfield. Basically, I embed the textfields in a scrollview and scroll upwards when the keyboard appears.</p>
<pre><code>// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, _activeField.frame.origin) ) {
[_scrollView scrollRectToVisible:_activeField.frame animated:YES];
}
}
</code></pre>
<p>However, when the textfield is already at the top of the view and there is no need for it to jump up, the above code causes it to jump up out of view.</p>
<p>Somewhere I recall reading that there is a line you can add to prevent that but I can't remember it. Basically, it would test if the textfield is already high enough up that the keyboard won't cover it and therefore, the view does not need to be moved.</p>
<p>The if statement in above code does not appear to be screening out cases where the textfield is not hidden.</p>
<p>Can anyone suggest a way to do this?</p>
<p>Thank you.</p>
| <p>If you are using autolayout, you should use constraints to manipulate the view instead of frames. You could try manipulating the bottom spacing of your textField or view to its superview as per your need and putting the <code>layoutIfNeeded</code> call inside an animation block. Also you can check if the value of your bottom constraint is already a particular value or pass a bool on <code>UIKeyboardWillHideNotification</code> and <code>UIKeyboardWillShowNotification</code>, if it is, then the value of the constraint should not change. Something like:</p>
<pre><code>-(void)showViewAnimatedly:(BOOL)show{
if(show){
[bottomConstraint setConstant:0];
}else{
[bottomConstraint setConstant:-160];
}
[UIView animateWithDuration:0.3f animations:^{
[self.view layoutIfNeeded];
}];
}
</code></pre>
<p>I would also recommend using <code>UIKeyboardWillShowNotification</code> instead of <code>UIKeyboardDidShowNotification</code> as the transition seems more in tune with the keyboard appearing. <code>UIKeyboardDidShowNotification</code> will start the transition AFTER keyboard appears. </p>
|
Images & Videos on Firebase Storage <p>I am trying to upload images and videos from the photos & videos storage on the phone to firebase storage and I have not been able to. And after being able to, I want to be able to post on a chat app to be seen like on twitter-- Android Studio. PLEASE HELP!!!</p>
| <p>Google for this youtube channel "TVAC Studio" and follow his firebase tutorials. It's insightful for beginners.</p>
<p>You won't be able to do a chat message app simply by follow his tutorial, but he doea a thorough run through for uploading and retrieving all the data you want (He teaches Audio files and images).</p>
<p>So after running through his video series, you'll only have to think about binding each file to the user who uploaded it and to think about how to bind messages and users to a chat node for the database.</p>
<p>Think thoroughly for the database structure.</p>
<p>Cheers</p>
|
Bootstrap - collapse one <ul> when another <ul> is expanded <p>assuming i have this</p>
<pre><code><li>
<a data-toggle="collapse">item 1</a>
</li>
<li>
<ul class="panel-collapse collapse">
<li>sub item 1</li>
<li>sub item 2</li>
</ul>
</li>
<li>
<a data-toggle="collapse">item 2</a>
</li>
<li>
<ul class="panel-collapse collapse">
<li>sub item 3</li>
<li>sub item 2</li>
</ul>
</li>
</code></pre>
<p>In the beginning, all the subitems are collapsed.
Now for example, when i click on item 1 and item 2, subitem 1, 2, 3, 4 will be expanded. This has been IMPLEMENTED.
Now i would like to have subitem 1 and 2 collapsed after i have subitem 3, 4 expanded. How do i archive that? Thanks.</p>
| <p><strong>Here is the demo</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-info">
<div class="panel-heading " role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#per" aria-expanded="true" aria-controls="collapseOne">
<strong>Link 1</strong>
</a>
</h4>
</div>
<!--To make by defualt open a any panel put class "in" (without quotes)-->
<div id="per" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body" style="padding:0px">
<ul class="list-group" style="margin-bottom: 0px;">
<li class="list-group-item">Link 1</li>
<li class="list-group-item">Link 1</li>
<li class="list-group-item">Link 1</li>
</ul>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#family" aria-expanded="false" aria-controls="collapseTwo">
<strong>Link 2</strong>
</a>
</h4>
</div>
<div id="family" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body" style="padding:0px">
<ul class="list-group"style=" margin-bottom: 0px;">
<li class="list-group-item">Link 2</li>
<li class="list-group-item">Link 2</li>
<li class="list-group-item">Link 2</li>
</ul>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading" role="tab" id="headingThree">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#social" aria-expanded="false" aria-controls="collapseThree">
<strong>Link 3</strong>
</a>
</h4>
</div>
<div id="social" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
<div class="panel-body" style="padding:0px">
<ul class="list-group" style=" margin-bottom: 0px;">
<li class="list-group-item">Link 3</li>
<li class="list-group-item">Link 3</li>
<li class="list-group-item">Link 3</li>
</ul>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
Beginning a game <p>I started a game, but there is something wrong with it. It actually don't shows anything and neither give me an error. It just run it and do nothing else.</p>
<p>Here are my codes:</p>
<p>CLASS</p>
<pre><code> package Game;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window extends Canvas{
private static final long serialVersionUID = -2408406005333728354L;
public Window(int height, int width, String title, Game game){
JFrame tit = new JFrame(title);
tit.setPreferredSize(new Dimension(width, height));
tit.setMaximumSize(new Dimension(width, height));
tit.setMinimumSize(new Dimension(width, height));
tit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //It make the game close up to the end without bugs
tit.setResizable(false); //not able to resize
tit.setLocationRelativeTo(null); //put the frame in the middle of the screen, originaly it starts up left
tit.add(game); // adding pur game class to the frame
tit.setVisible(true); //to make it visible
game.start(); // makes the game start
}
}
</code></pre>
<p>Here is the MAIN</p>
<pre><code> package Game;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID
= 1550691097823471818L;
public static final int WIDTH = 640, HEIGHT = WIDTH / 12*9;
private Thread thread;
private boolean running = false;
public Game(){
new Window(WIDTH, HEIGHT, "TITLE OF THAE GAME", this);
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
long lastTime = System.nanoTime();
double amoutOfTicks = 60.0;
double ns = 1000000000.0/amoutOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now-lastTime) / ns;
lastTime = now;
while (delta>=1){
tick();
delta--;
}
if(running)
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: "+ frames);
frames = 0;
}
}
stop();
}
private void tick(){
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.dispose();
bs.show();
}
public static void main(String[] args){
}
}
</code></pre>
<p>Actually there is something that I don't understand and it is the <code>serialVersionUID</code>. I don't know what this stuff is. I just copied it from this source: <a href="https://www.youtube.com/watch?v=1gir2R7G9ws&index=4&list=PL3j6S0UUuVMRSD1_wCzr2-Yd8h48rUvhs&t=647s" rel="nofollow">https://www.youtube.com/watch?v=1gir2R7G9ws&index=4&list=PL3j6S0UUuVMRSD1_wCzr2-Yd8h48rUvhs&t=647s</a></p>
<p>It is also the source i use to build those codes (copied).</p>
<p>Thank you for your time.</p>
| <p>You write nothing on your main method,so the program do nothing.you should new a Game object and a Window object ,then call the window method in the main method.</p>
|
Bootstrap accordion with Django: How to only load the data for the open accordion section? <p>I'm trying to make a webpage that will display recipes in the format of a bootstrap accordion like so (<a href="https://i.stack.imgur.com/1QEbG.png" rel="nofollow">see here</a>).
This is how I'm doing it as of now:</p>
<pre><code><div class="panel-group" id="accordion">
{% for recipe in recipes %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}">
{{ recipe }}
</a>
</h4>
</div>
<div id="collapse{{ forloop.counter }}" class="panel-collapse collapse">
<div class="panel-body">
<table class="table table-hover">
{% for ingredient in foodtype|ingredients_in_recipe:recipe %}
<tr>
<td>
{{ ingredient.ingredient_name }}
</td>
<td>
{{ ingredient.ingredient_quantity }}
</td>
</tr>
{% endfor %}
<p>{{ recipe.details }}</p>
</table>
</div>
</div>
</div>
{% endfor %}
</div>
</code></pre>
<p>I have made a custom template tag for this like so:</p>
<pre><code>@register.filter
def ingredients_in_recipe(foodtype, recipe):
return foodtype.ingredient_set.filter(recipe=recipe).order_by("ingredient_name")
</code></pre>
<p>The problem is that I have 200+ recipes and loading all this data is way too slow. Ideally the template tag function ingredients_in_recipe should only be called when the user clicks on the recipe. However from my understanding this isn't possible because Django runs it all then sends the rendered HTML to the user.</p>
<p>Is there anyway I could circumvent this issue whilst still keeping the accordion style like in the picture?</p>
<p>Thanks in advance,
Max</p>
<p><strong>EDIT:</strong> Here's my view as well</p>
<pre><code>def detail(request, foodtype_id):
foodtype = get_object_or_404(foodtype, id=foodtype_id)
recipe = foodtype.recipe_set.values_list('recipe').order_by('recipe').distinct()
context = {
'foodtype': foodtype,
'recipe': recipe,
}
return render(request, 'main/detail.html', context)
</code></pre>
| <p>Always better to do that logic before it gets to the template. What if you set the ordering on ingredients so then you won't have to order them in the template? Does that work and improve the performance?</p>
<pre><code>class Ingredient(models.Model):
...
class Meta:
ordering = ['ingredient_name']
<div class="panel-group" id="accordion">
{% for recipe in recipes %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}">
{{ recipe }}
</a>
</h4>
</div>
<div id="collapse{{ forloop.counter }}" class="panel-collapse collapse">
<div class="panel-body">
<table class="table table-hover">
{% for ingredient in recipe.ingredient_set.all %}
<tr>
<td>
{{ ingredient.ingredient_name }}
</td>
<td>
{{ ingredient.ingredient_quantity }}
</td>
</tr>
{% endfor %}
<p>{{ recipe.details }}</p>
</table>
</div>
</div>
</div>
{% endfor %}
</div>
</code></pre>
|
Consuming Asp.Net Core api locally <p>I don't know if my google skills are diminishing or what but I can't seem to figure out how to consume a local api. This may be best explained with sample code...</p>
<p>So I have a simple api</p>
<pre><code>public class FooApiController : Controller
{
public IActionResult GetFoo(int id)
{
if (id == 0)
return BadRequest();
var data = ... do db access
return Ok(data);
}
}
</code></pre>
<p>and a view controller</p>
<pre><code>public class FooController : Controller
{
public IActionResult Foo()
{
var api = new FooApiController();
var data = api.GetFoo(1);
ViewBag.Data = data;
return View();
}
}
</code></pre>
<p>So in the above view controller I call the api to get the data needed. However, being that the api controller returns an IActionResult, ViewBad.Data ends up being an IActionResult object. So how do I change the above to check the StatusCode of the api call, handle errors if need be, and if not... put just the data into the ViewBag, instead of the entire result object.</p>
<p>Every sample I have found seems to have the view controller return a view that then uses an ajax call to get the data. While I understand and could easily do that, I don't like the idea of making 2 round trips to the server when I don't need to.</p>
| <p>You are doing it wrong.
If you want to reuse the code among multiple controllers, then it is better to move it from the GetFoo method and put it into a shared class and access it from everywhere else.</p>
<p>If you want to call it from a view through REST, then call it using $.ajax
ex: </p>
<pre><code>$.ajax('FooApi/GetFoo/5',function(data){alert(data);});
</code></pre>
<p>If you want to access it from another C# client, then use the <code>HttpClient</code> class, ex:</p>
<pre><code> HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("api/FooApi/GetFoo", 3);
response.EnsureSuccessStatusCode();
</code></pre>
|
Can I use PyQt for both C++ and Python? <p>I'd like to learn Qt both on Python and C++. I am on Windows.</p>
<p>Is instaling PyQT5 with <code>pip3 install pyqt5</code> enough for C++ development or do I still have to install both Qt and PyQt?</p>
<p>How do I do the second option?</p>
| <p>For C++ development you're going to need a C++ compiler. On Windows Qt supports both the Mingw and Visual Studio toolchains. From there, I don't believe pyqt includes the header files you're going to need for C++ development and I cannot say for certain what toolchain it was compiled with. </p>
<p>Your best bet is either install the official Qt binaries for your compiler, or build the binaries from source (the later will take some time and effort.)</p>
<p>If you want to mix both C++ and Python in a single Qt project, check out <a href="https://www.riverbankcomputing.com/software/sip/intro" rel="nofollow">SIP bindings</a>.</p>
<p>Another thing to keep in mind is that pyqt5 comes with the LGPL licensed version of Qt by default. This may or may not be appropriate for your project(s), but StackOverflow isn't intended to discuss licensing issues.</p>
|
SSL: Client Authentication, multiple certificate version in same store <p>Here is the situation:</p>
<ol>
<li><p>Our Application talks to multiple 3rd party applications and few of them need client authentication.</p></li>
<li><p>One particular third party app needs client auth and has appropriately provided certificates (<em>which we imported in our key store (JKS)</em>). This is during integration testing. Things are working fine in the Test environment.</p></li>
<li><p>Now before going live, they want to upgrade the certificate issued by an CA.</p></li>
<li><p>For the new certificate, we can always create a new store, but for the sake
of convenience wanted to know if the two certificates(<em>old and new</em>) can reside in the same store? (<em>So that in case they rollback, there is no change on our side</em>)</p></li>
<li><p>URL being same, how does the application(http-client library) knows which client certificate(s) version to present when making calls to server? </p></li>
</ol>
| <p>You can have both certificates in the truststore. JSSE will select whichever one matches the trusted CAs the server advises when it requests the client certificate.</p>
<p>However the scenario you describe is radically insecure. If you are the client, you should be providing your own client certificate, not one that comes from someone else. Otherwise there must be a compromise of the private key, which means the certificate can't be used for the purpose it is intended for, and you can legally repudiate all transactions that are supposedly authenticated via this means. Client authentication under such a scheme serves no useful purpose whatsoever and you should not waste further time on it.</p>
|
python receive image over socket <p>I'm trying to send an image over a socket - I'm capturing an image on my raspberry pi using pycam, sending to a remote machine for processing, and sending a response back.</p>
<p>On the server (the pi), I'm capturing the image, transforming to an array, rearranging to a 1D array and using the tostring() method.</p>
<p>On the server, the string received is not the same length. Any thoughts on what is going wrong here? Attached is the code I'm running, as well as the output on both the server and the client</p>
<p>SERVER CODE:</p>
<pre><code>from picamera.array import PiRGBArray
from picamera import PiCamera
import socket
import numpy as np
from time import sleep
import sys
camera = PiCamera()
camera.resolution = (640,480)
rawCapture = PiRGBArray(camera)
s = socket.socket()
host = 'myHost'
port = 12345
s.bind((host,port))
s.listen(1)
while True:
c,addr = s.accept()
signal = c.recv(1024)
print 'received signal: ' + signal
if signal == '1':
camera.start_preview()
sleep(2)
camera.capture(rawCapture, format = 'bgr')
image = rawCapture.array
print np.shape(image)
out = np.reshape(image,640*480*3)
print out.dtype
print 'sending file length: ' + str(len(out))
c.send(str(len(out)))
print 'sending file'
c.send(out.tostring())
print 'sent'
c.close()
break
</code></pre>
<p>CLIENT CODE:</p>
<pre><code>import socket, pickle
import cv2
import numpy as np
host = '192.168.1.87'
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send('1')
#while true:
x = long(s.recv(1024))
rawPic = s.recv(x)
print 'Received'
print x
print len(rawPic)
type(rawPic)
#EDITED TO INCLUDE DTYPE
image = np.fromstring(rawPic,np.uint8)
s.close()
</code></pre>
<p>SERVER OUTPUT:</p>
<pre><code>received signal: 1
(480, 640, 3)
uint8
sending file length: 921600
sending file
</code></pre>
<p>CLIENT OUTPUT:</p>
<pre><code>Received
921600
27740
str
ValueError Traceback (most recent call last)
<ipython-input-15-9c39eaa92454> in <module>()
----> 1 image = np.fromstring(rawPic)
ValueError: string size must be a multiple of element size
</code></pre>
<p>I'm wondering if the issue is i'm calling tostring() on a uint8, and if the fromstring() is assuming it's a uint32? I can't figure out why the received string is so much smaller than what is sent. </p>
<p><strong>EDIT</strong>
It seems for some reason the server is not fully sending the file. It never prints 'sent', which it should do at completion. If I change the send line to:</p>
<pre><code>c.send(str(len(out[0:100])))
print 'sending file'
c.send(out[0:100].tostring())
</code></pre>
<p>Everything works fine. Thoughts on what could be cutting off my sent file midway through?</p>
| <h1>Decoding to the Proper Type</h1>
<p>When you call <code>tostring()</code>, datatype (and shape) information is lost. You must supply numpy with the datatype you expect.</p>
<p>Ex:</p>
<pre><code>import numpy as np
image = np.random.random((50, 50)).astype(np.uint8)
image_str = image.tostring()
# Works
image_decoded = np.fromstring(image_str, np.uint8)
# Error (dtype defaults to float)
image_decoded = np.fromstring(image_str)
</code></pre>
<h1>Recovering Shape</h1>
<p>If shape is always fixed, you can do</p>
<pre><code>image_with_proper_shape = np.reshape(image_decoded, (480, 640, 3))
</code></pre>
<p>In the client.</p>
<p>Otherwise, you'll have to include shape information in your message, to be decoded in the client.</p>
|
Why is python trying to ASCII encode my unicode string for Mysqldb? <p>Yes, again a question about unicode and Python. I thought I've read it all and adopted good programming practice after you guys opened my mind about Unicode,but this error came back at me :</p>
<pre><code>'ascii' codec can't encode character u'\xc0' in position 24: ordinal not in range(128)
</code></pre>
<p>I'm using scrapy with Python 2.7, so whats coming from "outside world" are web page properly decoded and processed with xpath as can be seen by an empty error log coming from those checks just before the exception:</p>
<pre><code>if not isinstance(key, unicode):
logging.error(u"Key is not unicode: %s" % key)
if not isinstance(value, unicode):
logging.error(u"value is not unicode: %s" % value)
if not isinstance(item['listingId'], int):
logging.error(u"item['listingId'] is not an int:%s" % item['listingId'])
</code></pre>
<p>But then, when the MySql transaction is hapening on the next line:</p>
<pre><code>d = txn.execute("INSERT IGNORE INTO `listingsDetails` VALUE (%s, %s, %s);", (item['listingId'], key, value))
</code></pre>
<p>I still get this exception from time to time. (1% of pages)
Notice the "pipeline.py" line 403 which is the MySql INSERT.</p>
<pre><code>2016-10-16 22:22:10 [Listings] ERROR: [Failure instance: Traceback: <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xc0' in position 24: ordinal not in range(128)
/usr/lib/python2.7/threading.py:801:__bootstrap_inner
/usr/lib/python2.7/threading.py:754:run
/usr/lib/python2.7/dist-packages/twisted/_threads/_threadworker.py:46:work
/usr/lib/python2.7/dist-packages/twisted/_threads/_team.py:190:doWork
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py:246:inContext
/usr/lib/python2.7/dist-packages/twisted/python/threadpool.py:262:<lambda>
/usr/lib/python2.7/dist-packages/twisted/python/context.py:118:callWithContext
/usr/lib/python2.7/dist-packages/twisted/python/context.py:81:callWithContext
/usr/lib/python2.7/dist-packages/twisted/enterprise/adbapi.py:445:_runInteraction
/home/mrme/git/rep/scrapy_prj/firstproject/firstproject/pipelines.py:403:_do_upsert
/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py:228:execute
/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py:127:_warning_check
/usr/lib/python2.7/logging/__init__.py:1724:_showwarning
/usr/lib/python2.7/warnings.py:50:formatwarning
</code></pre>
<p>I've opened the MySql connection with:</p>
<pre><code>dbargs = dict(
host=settings['MYSQL_HOST'],
db=settings['MYSQL_DBNAME'],
user=settings['MYSQL_USER'],
passwd=settings['MYSQL_PASSWD'],
charset='utf8',
use_unicode=True
)
dbpool = adbapi.ConnectionPool('MySQLdb', **dbargs)
</code></pre>
<p>I also tried to add this after connection as per MySql documentation:</p>
<pre><code>self.dbpool.runOperation("SET NAMES 'utf8'", )
self.dbpool.runOperation("SET CHARSET 'utf8'",)
</code></pre>
<p>And confirmed my database is correctly setup with:</p>
<pre><code>SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name;
character_set_client: utf8mb4
character_set_connection: utf8mb4
character_set_database: utf8
character_set_filesystem: binary
character_set_results: utf8mb4
character_set_server: latin1
character_set_system: utf8
</code></pre>
<p>Who the hell is trying to encode in Ascii here?</p>
<p>Every 2cents is welcomed ;-)</p>
<p>If its of any help, all other accent character are fine in the database. Only this u'\xc0' = Ã is problematic.</p>
| <p>you can put following code if exception come.</p>
<pre><code>varName = ''.join([i if ord(i) < 128 else ' ' for i in strName])
</code></pre>
<p>here, strName is string which contains Non ascii value</p>
|
What aren't my checkboxes responding individually? <p>So the issue I am having is that my checkboxes in my JS game isn't responding to individual clicks. When I console.log, I get index 0 every time, no matter which box I click and a non responsive check box. However, the level functions are responding.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> window.onload = function() {
console.log('DOM is loaded');
fillAll = function() {
// event.preventDefault();
for (var i = 0; i < 25; i++) {
document.bulbform.elements[i].checked = 1;
}
};
clearAll = function() {
for (var i = 0; i < 25; i++) {
document.bulbform.elements[i].checked = 0;
}
};
levelOne = function() {
clearAll();
document.bulbform.elements[10].checked = 1;
document.bulbform.elements[12].checked = 1;
document.bulbform.elements[14].checked = 1;
};
levelTwo = function() {
clearAll();
document.bulbform.elements[12].checked = 1;
document.bulbform.elements[16].checked = 1;
document.bulbform.elements[17].checked = 1;
document.bulbform.elements[18].checked = 1;
document.bulbform.elements[20].checked = 1;
document.bulbform.elements[21].checked = 1;
document.bulbform.elements[22].checked = 1;
document.bulbform.elements[23].checked = 1;
document.bulbform.elements[24].checked = 1;
};
levelThree = function() {
fillAll();
document.bulbform.elements[4].checked = 0;
document.bulbform.elements[6].checked = 0;
document.bulbform.elements[7].checked = 0;
document.bulbform.elements[8].checked = 0;
document.bulbform.elements[11].checked = 0;
document.bulbform.elements[12].checked = 0;
document.bulbform.elements[13].checked = 0;
document.bulbform.elements[16].checked = 0;
document.bulbform.elements[17].checked = 0;
document.bulbform.elements[18].checked = 0;
document.bulbform.elements[24].checked = 0;
};
levelFour = function() {
clearAll();
document.bulbform.elements[2].checked = 1;
document.bulbform.elements[6].checked = 1;
document.bulbform.elements[8].checked = 1;
document.bulbform.elements[10].checked = 1;
document.bulbform.elements[12].checked = 1;
document.bulbform.elements[14].checked = 1;
document.bulbform.elements[16].checked = 1;
document.bulbform.elements[18].checked = 1;
document.bulbform.elements[22].checked = 1;
};
levelFive = function() {
clearAll();
document.bulbform.elements[11].checked = 1;
document.bulbform.elements[16].checked = 1;
document.bulbform.elements[21].checked = 1;
};
checkAll = function() {
var win = 1;
for (var i = 0; i < 25; i++) {
if (document.bulbform.elements[i].checked == 1) {
win = 0;
}
}
if (win == 1) {
alert("You Won!");
}
};
check = function(v) {
a = parseInt(v);
// console.log(parseInt(a));
// console.log(typeof(a));
if (document.bulbform.elements[v].checked == 1) {
document.bulbform.elements[v].checked = 0;
} else {
document.bulbform.elements[v].checked = 1;
}
checkAll();
};
};</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="row">
<div class="col s12 m6">
<div class="card-panel blue-grey lighten-3">
<form name="bulbform">
<!-- Row One -->
<input type="checkbox" value="0" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="1" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="2" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="3" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="4" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<!-- Row Two -->
<input type="checkbox" value="5" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="6" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="7" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="8" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="9" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<!-- Row Three -->
<input type="checkbox" value="10" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="11" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="12" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="13" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="14" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<!-- Row Four -->
<input type="checkbox" value="15" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="16" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="17" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="18" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="19" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<!-- Row Five -->
<input type="checkbox" value="20" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="21" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="22" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="23" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<input type="checkbox" value="24" onclick="javascript:check(value)" class="filled-in" id="filled-in-box" checked="1" />
<label for="filled-in-box"></label>
<br>
<!-- Stat Game Levels -->
<a href="javascript:levelOne()" class="waves-effect waves-teal btn-flat">Level 1</a>
<a href="javascript:levelTwo()" class="waves-effect waves-teal btn-flat">Level 2</a>
<a href="javascript:levelThree()" class="waves-effect waves-teal btn-flat">Level 3</a>
<a href="javascript:levelFour()" class="waves-effect waves-teal btn-flat">Level 4</a>
<a href="javascript:levelFive()" class="waves-effect waves-teal btn-flat">Level 5</a>
<!-- End Game Levels -->
<br>
<button class="btn waves-effect waves-light btn-large" type="reset" value="clear" name="action">Clear
<i class="material-icons left">lightbulb_outline</i>
</button>
</div>
</div>
</div>
<script type="text/javascript" src="game.js"></script>
</body></code></pre>
</div>
</div>
</p>
| <p>Dai has good advice, but your actual issue is here:</p>
<pre><code>... onclick="javascript:check(value)" ...
</code></pre>
<p>There no global <em>value</em> variable so you're passing <em>undefined</em>, which evaluates to 0. What you actually want to pass is the value of the checkbox:</p>
<pre><code>... onclick="javascript:check(this.value) ...
</code></pre>
<p>Oh, also:</p>
<blockquote>
<p>checkboxes in my JS game isn't responding to individual clicks</p>
</blockquote>
<p>because you're doing:</p>
<pre><code>if (document.bulbform.elements[v].checked == 1) {
document.bulbform.elements[v].checked = 0;
} else {
document.bulbform.elements[v].checked = 1;
}
</code></pre>
<p>So if the checkbox is unchecked and then clicks on it, it's state in the listener is checked, so you uncheck it again. And <em>vice versa</em> if it's checked (the user clicks, unchecks it, then the listener checks it again). This is nonsensical, just remove the listener and let the checkbox be a checkbox by itself.</p>
|
Which class get inherited when using nested class <pre><code>class Admin::ApplicationController < ApplicationController
def index
end
end
</code></pre>
<p>Which class get inherited when I using nested class?</p>
<pre><code>class Admin < ApplicationController
class ApplicationController
end
end
</code></pre>
<p>or </p>
<pre><code>class Admin
class ApplicationController < ApplicationController
end
end
</code></pre>
<p>I think the second one is the winner, because what I understand <code>Admin::ApplicationController < ApplicationController</code> is get the <code>ApplicationController</code> inside <code>Admin</code> namespace and make it inherit from <code>ApplicationController</code>.</p>
| <p>If the question is what is the equivalent of this line:</p>
<pre><code>class Admin::ApplicationController < ApplicationController
</code></pre>
<p>Then your second assumption is correct, it is equivalent to:</p>
<pre><code>class Admin
class ApplicationController < ApplicationController
end
end
</code></pre>
<p>Few sidenotes though:</p>
<ol>
<li>Your current design exposes bad naming</li>
<li>Why not make <code>Admin</code> a module instead of class?</li>
<li>Prefer using the explicit form instead of nested one - you'll never get confused.</li>
<li>See <a href="http://stackoverflow.com/questions/34338131/why-doesnt-ruby-find-classes-in-a-higher-scope-when-module-is-specified-using">this thread</a> about some difference in levels of nesting between two forms of class definitions.</li>
</ol>
|
Tomcat 8 - Database realm configuration <p>I have configured tomcat 7 server to use MD5 digest in database realm configuration.
It worked fine.
Now I need to upgrade my servers to tomcat 8.
But it generates a different hash for my my passwords in database.
How can I configure it to generate same old values?
I have already copied jdbc driver jars to lib folder in tomcat 8 and made all sh files in bin executable.</p>
<p>In simple, how can I make below two outputs equal.
Tomcat 7:</p>
<pre><code>~/apache-tomcat-7.0.69/bin$ ./digest.sh -a MD5 test
Listening for transport dt_socket at address: 5005
test:098f6bcd4621d373cade4e832627b4f6
~/apache-tomcat-7.0.69/bin$
</code></pre>
<p>Tomcat 8:</p>
<pre><code>~/apache-tomcat-8.5.6/bin$ ./digest.sh -a MD5 test
test:27d6262696d98e0a8a973d43eef07c66c68b089a4ada21dd3ba0defc04ca302e$1$13a7c1932523dcea3bb39ef05b75b4c6
~/apache-tomcat-8.5.6/bin$
</code></pre>
<p>Thanks</p>
| <p>Finally <a href="http://%20http://stackoverflow.com/a/38937341/4595123" rel="nofollow">this</a> solved my question.</p>
<p>To answer the first point, here's a comparison of the from my context.xml before and after the switch to Tomcat 8:</p>
<p><strong>Before:</strong></p>
<pre><code><Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/myDataSource"
roleNameCol="role" userCredCol="password" userNameCol="loginid"
digest="md5"
userRoleTable="userroles" userTable="users"
localDataSource="true" />
</code></pre>
<p><strong>After:</strong></p>
<pre><code><Realm className="org.apache.catalina.realm.DataSourceRealm"
dataSourceName="jdbc/myDataSource"
roleNameCol="role" userCredCol="password" userNameCol="loginid"
userRoleTable="userroles" userTable="users" localDataSource="true">
<CredentialHandler
className="org.apache.catalina.realm.MessageDigestCredentialHandler"
algorithm="md5" />
</Realm>
</code></pre>
|
How do I print a variable within a class' if statement? <p>I'm trying to print a variable in Python using the following code:</p>
<pre><code>from time import sleep
import random
class Hero:
def __init__(self,name):
self.name = name
if name == "rock":
self.health = 50
self.attack = 10
elif name == "paper":
self.health = 70
self.attack = 7
elif name == "scissors":
self.health = 100
self.attack = 5
def dmg(self, other):
other.ehealth -= self.attack
start = 1
while start == 1:
name = input("Pick a class [rock/paper/scissors]")
if name != "rock" or "paper" or "scissors":
print ("That player does not exist. Try again.")
start = 1
else:
start = 1
player = Hero(name)
enemyName = ["erock", "epaper", "escissors"]
ename = random.choice(enemyName)
print ("Your character is", name, "which comes with", self.health, "health, and", self.attack, "attack.")
print("")
sleep(1)
print ("Your enemy is", ename, "which comes with", ehealth, "health, and", eattack, "attack.")
</code></pre>
<p>I can't figure out a way to access and print the variable "self.health" under the "Hero" class. I can access "name" just fine. Maybe it's the fact that it's under an if statement? Can someone help me out?</p>
| <p><code>self</code> is just a parameter name used inside the methods. Don't use it outside the method.</p>
<p>To access the variables refer to them using the object name (<code>player</code>) like this</p>
<pre><code>player.health
</code></pre>
<p>The <code>name</code> variable you are printing "works" because it's not from the object. You should use the same notation to access that too:</p>
<pre><code>player.name
</code></pre>
|
Nodejs delete folder on Amazon S3 with aws-sdk <p>I'm facing issue of deleting folder which contains photos inside on Amazon S3</p>
<p>1. Create folder</p>
<pre><code>var params = {Bucket: S3_BUCKET, Key: "test/", ACL:"public-read"};
s3.putObject(params, function(err, data) {
});
</code></pre>
<p>2. Upload photo</p>
<pre><code>var body = fs.createReadStream(filePath);
var params = {Bucket: S3_BUCKET, Key: "test/flower.jpgg", Body: body, ContentType:"image/jpeg", ACL:"public-read"};
s3.upload(params, function(err, data) {
});
</code></pre>
<p>3. Delete folder </p>
<pre><code>var params = {Bucket: S3_BUCKET, Key: "test/"};
s3.deleteObject(params, function(err, data) {
});
</code></pre>
<p>If folder has no photo, delete function works well. But it contains photos, delete will not work.<br>
Please help. Thank for all supports.</p>
| <p>The problem here is a conceptual one, and starts at step 1. </p>
<p>This does not create a folder. It creates a placeholder object that the console will display as a folder. </p>
<blockquote>
<p>An object named with a trailing "/" displays as a folder in the Amazon S3 console. </p>
<p><a href="http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html" rel="nofollow">http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html</a></p>
</blockquote>
<p>It's not necessary to do this -- creating objects with this key prefix will <em>still</em> cause the console to display a folder, even without creating this object. From the same page:</p>
<blockquote>
<p>Amazon S3 has a flat structure with no hierarchy like you would see in a typical file system. However, for the sake of organizational simplicity, the Amazon S3 console supports the folder concept as a means of grouping objects. Amazon S3 does this by using key name prefixes for objects.</p>
</blockquote>
<p>Since, at step 1, you are not actually creating a folder, it makes sense that removing the placeholder object also does not delete the folder.</p>
<p>Folders do not actually exist in S3 -- they're just used for display purposes in the console -- so objects cannot properly be said to be "in" folders. The only way to remove all the objects "in" a folder is to explicitly remove the objects individually. Similarly, the only way to rename a folder is to rename a folder is to rename the objects in it... and the only way to rename an object is to make a copy of an the object with a new key and then delete the old object.</p>
|
Why don't we need to perform modulo operation on every operands in Fast Power algorithm? <p>Today I practiced with a puzzle "fast power", which used a formula:
<code>(a * b) % p = (a % p * b % p) % p</code> to calculate <code>(a^n)%p</code>, something like that: <code>2^31 % 3 = 2</code></p>
<p>However, I am so confused when I found the answer used <code>((temp * temp) % b * a) % b;</code> to solved situation when n is odd, like <code>2^3</code></p>
<p>(temp is <code>(temp * temp) % b * a</code> recursively or <code>(temp * temp) % b</code>).</p>
<p>Should not it be <code>((temp * temp) % b * a%b) % b</code>?</p>
<p>Since according to this formula, everything should <code>%b</code> before times together.</p>
| <blockquote>
<p>Should not it be <code>((temp * temp) % b * a % b) % b</code>?</p>
</blockquote>
<p>No. For <code>a</code>, if you know beforehand that <code>a</code> won't overflow(a is smaller than b), you don't have to mod it.</p>
<p>The idea is <a href="https://en.wikipedia.org/wiki/Modular_arithmetic" rel="nofollow">modular arithmetic</a> works for addition and multiplication.
Operation like <code>(a + b) % M = (a % M + b % M) % M</code> and <code>(a * b) % M = (a % M * b % M) % M</code> are generally performed to avoid overflow of <code>(a * b)</code> and <code>(a + b)</code> and keep the value under certain range.</p>
<p>Example:</p>
<pre><code>const int Mod = 7;
int a = 13;
int b = 12;
int b = b % Mod; // b now contains 5 which is certainly smaller than Mod
int x = (a % Mod * b) % Mod; // you won't need to mod b again if you know beforehand b is smaller than Mod
</code></pre>
<h2>Update</h2>
<p>C++ implementation of power function:</p>
<pre><code>#define MOD 1000000007
// assuming x and n both be positive and initially smaller than Mod
int power(int x, int n) {
if(n == 0) return x;
int half = power(x, n / 2) % Mod;
int ret = (half * half) % Mod; // you didn't need to do (half % Mod * half % Mod) % Mod because you already know half is smaller than Mod and won't overflow.
// Modulas being performed on the multiplied output, so now ret will be smaller than Mod
if(n & 1) {
ret = (ret * x) % Mod; // you didn't need to do (ret % Mod * x % Mod) % Mod
// because you already know ret and x is smaller than Mod
}
return ret;
}
</code></pre>
<p>Mod is an expensive operation. So you should avoid it whenever possible.</p>
|
JAVA: Game of Craps making sure what printed is correct <p>I have an assignment for my programming course. I have only one issue which I cannot figure out.</p>
<p>My instructions are the following: Write a program that simulates how often a player would win if they rolled the dice 100 times. If the players rolls a 7, or 11 they win</p>
<p>My Problem is the following: My program is showing that I'm winning more times than I should be. I only want my program to print out the message that the user has won, if they have a seven or an eleven, but that isn't happening. Could anyone give me some advice on what I might need to do?</p>
<p>Below is my code. Thank you very much in advance for your help. </p>
<pre><code> @author Jordan Navas
@version 1.0
COP2253 Workshop7
File Name: Craps.java
*/
import java.util.Random;
public class Craps
{
public static void main(String[] args)
{
Random rand = new Random();
int gamesWon=0;
int gamesLost=0;
for(int i=1;i<=100;i++)
{
craps(rand);
if(craps(rand))
{
gamesWon++;
}
else{
gamesLost++;
}
}
System.out.println("Games You Have Won: " + gamesWon);
System.out.println("Games You Have Lost: " + gamesLost);
}
public static boolean craps(Random rand)
{
int firstDice = rand.nextInt(6)+1;
int secondDice = rand.nextInt(6+1);
int sumOfDies = firstDice + secondDice;
System.out.print("[" + firstDice + "," + secondDice + "]");
if (sumOfDies == 7 || sumOfDies == 11)
{
System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations! ");
return true;
} else if(sumOfDies == 2 || sumOfDies == 3 || sumOfDies == 12)
{
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
int point = sumOfDies;
System.out.print("Point: " + point + " ");
if (sumOfDies == point)
{
System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations!");
return true;
} else
{
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
}
}
</code></pre>
| <p>I think you dont need following if condition in your code.</p>
<pre><code>if (sumOfDies == point) { System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations!"); return true; }
</code></pre>
<p>infact all you need in your code is following condition.</p>
<pre><code>if (sumOfDies == 7 || sumOfDies == 11) { System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations! "); return true; }
else { System.out.println(sumOfDies + " Congratulations! You Lost! "); return false; }
</code></pre>
<p>here is how your function should work:</p>
<pre><code> public static boolean craps(Random rand) {
int firstDice = rand.nextInt(6)+1;
int secondDice = rand.nextInt(6+1);
int sumOfDies = firstDice + secondDice;
System.out.print("[" + firstDice + "," + secondDice + "]");
if (sumOfDies == 7 || sumOfDies == 11) {
System.out.println(sumOfDies + " You Won! Congratulations! You Won! Congratulations! ");
return true;
} else {
System.out.println(sumOfDies + " Congratulations! You Lost! ");
return false;
}
}
</code></pre>
|
swift how to make phone call iOS 10? <p>I want my app to be able to call a certain number when a button is clicked. I've tried to google it but there doesn't seem to have one for iOS 10 so far (where openURL is gone). Can someone put an example for me on how to do so? For instance like: </p>
<pre><code>@IBAction func callPoliceButton(_ sender: UIButton) {
// Call the local Police department
}
</code></pre>
| <p>You can call like this if you want a popup</p>
<pre><code>if let url = URL(string: "telprompt://\(number)") {
UIApplication.shared.openURL(url)
}
</code></pre>
<p>else if you want to call direct </p>
<pre><code> if let url = URL(string: "tel://\(number)") {
UIApplication.shared.openURL(url)
}
</code></pre>
<p>For Swift 3 you can use like</p>
<pre><code>guard let number = URL(string: "telprompt://" + number) else { return }
UIApplication.shared.open(number, options: [:], completionHandler: nil)
</code></pre>
|
How to extract child of node in data snapshot <p>My firebase set up is as such:</p>
<pre><code>Parent_node:{
Type:{
1476663471800:{ //This is a timestamp = Int64(date.timeIntervalSince1970 * 1000.0)
uid: USERS_UID;
}
}
}
</code></pre>
<p>how would I access the users uid? I have tried the following code, but its not extracting the UID </p>
<pre><code>self.databaseRef.child("Parent_node/\(Type)").queryLimitedToLast(5).observeEventType(.Value, withBlock: { (snapshot) in
print(snapshot)
if let userDict = snapshot.value as? [String:AnyObject]{
for each in userDict{
let uidExtraced = each
print(uidExtraced)
//("1476663471700", [uid: USERS_UID])
</code></pre>
| <p>First of all use <code>snapshot.value?.allValues</code> to get values and than parse it...</p>
<pre><code> if snapshot.exists() {
for value in (snapshot.value?.allValues)!{
print(value) // you get [uid: USERS_UID] here
// ... parse it to get USERS_UID
print("user_id -- \(value["uid"])")
}
}
</code></pre>
<blockquote>
<p>With this method, order of child might be different. For ordered nodes, you can use <code>snapshot.child</code></p>
</blockquote>
|
Deserialize error with adding more serialized variables for saving/loading in Unity <p>I have been messing around with saving and loading in Unity in which I save a serialized class to a file. I have a Serializable class :</p>
<pre><code>[Serializable]
class Save
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
}
</code></pre>
<p>and save it to a file A-OK. I can load it with no errors but if I wanted to add later :</p>
<pre><code>[Serializable]
class Save
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int extra = 0;
}
</code></pre>
<p>and I run my scripts it gives me a deserialization error which I completely understand as when I cast the deserialized file to my new class 'Saved' the new variable I added doesn't exist and it gives me the error. </p>
<p>I found this error when I was fixing an Asset in the store and I know one fix can be just change the filename so a new file is created but I don't just want to wipe the contents of what was saved before. </p>
<p>So my question is, if I wanted to add more variables to my serialized class how would I catch and adjust to old versions of it if people were to update the asset?</p>
<p>Thanks!</p>
| <p>This problem is known when using C# serializer. Convert the data to Json with <code>JsonUtility</code> then save it with the <code>PlayerPrefs</code>. When loading, load with the <code>PlayerPrefs</code> then convert the json back to class with <code>JsonUtility</code>.</p>
<p>Example class to Save:</p>
<pre><code>[Serializable]
public class Save
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int extra = 0;
public float highScore = 0;
}
</code></pre>
<p><strong>Save Data</strong>:</p>
<pre><code>void Save()
{
Save saveData = new Save();
saveData.extra = 99;
saveData.highScore = 40;
//Convert to Json
string jsonData = JsonUtility.ToJson(saveData);
//Save Json string
PlayerPrefs.SetString("MySettings", jsonData);
PlayerPrefs.Save();
}
</code></pre>
<p><strong>Load Data</strong>:</p>
<pre><code>void Load()
{
//Load saved Json
string jsonData = PlayerPrefs.GetString("MySettings");
//Convert to Class
Save loadedData = JsonUtility.FromJson<Save>(jsonData);
//Display saved data
Debug.Log("Extra: " + loadedData.extra);
Debug.Log("High Score: " + loadedData.highScore);
for (int i = 0; i < loadedData.ID.Count; i++)
{
Debug.Log("ID: " + loadedData.ID[i]);
}
for (int i = 0; i < loadedData.Amounts.Count; i++)
{
Debug.Log("Amounts: " + loadedData.Amounts[i]);
}
}
</code></pre>
<p>Difference between <code>JsonUtility.FromJson</code> and <code>JsonUtility.FromJsonOverwrite</code>:</p>
<p><strong>A</strong>.<code>JsonUtility.FromJson</code> creates new Object from Json and returns it. It allocates memory.</p>
<pre><code>string jsonData = PlayerPrefs.GetString("MySettings");
//Convert to Class. FromJson creates new Save instance
Save loadedData = JsonUtility.FromJson<Save>(jsonData);
</code></pre>
<p><strong>B</strong>.<code>JsonUtility.FromJsonOverwrite</code> does <strong>not</strong> create new Object. It has nothing to do with adding more datatype to your class. It just overwrite the data that is passed in it. It's good for memory conservation and less GC. The only time it will allocate memory if when you have fields such as <code>array</code>, <code>string</code> and <code>List</code>. </p>
<p>Example of where <code>JsonUtility.FromJsonOverwrite</code> should be used is when performing constant data transfer with Json. It will improve performance.</p>
<pre><code>//Create Save instance **once** in the Start or Awake function
Save loadedData = null;
void Start()
{
//loadedData instance is created once
loadedData = new Save();
}
void Load()
{
string jsonData = PlayerPrefs.GetString("MySettings");
//Convert to Class but don't create new Save Object. Re-use loadedData and overwrite old data in it
JsonUtility.FromJsonOverwrite(jsonData, loadedData);
Debug.Log("High Score: " + loadedData.highScore);
}
</code></pre>
|
Concerned about JWT security <p>Recently, I implemented the JWT strategy using passport and node.js... however, I am beginning to worry about the concept in general. Isn't it true that once someone has access to the JWT, it can be used to retrieve protected data? And isn't gaining access to the JWT, as easy as using chrome dev tools?</p>
<p>I could try and reduce the expiry date, however... isn't it true that as long as the user details are the same, the token generated will also be the same every time? So what's the point of the expiry date, if you are going to end up with the same token anyway? I am sure that I missing the point here somewhere. Guidance would be appreciated. Thanks.</p>
| <blockquote>
<p>Isn't it true that once someone has access to the JWT, it can be used to retrieve protected data? And isn't gaining access to the JWT, as easy as using chrome dev tools?</p>
</blockquote>
<p>Generally speaking, it shouldn't be an issue if the user can access <em>their own</em> JWT -- because they're the one who is allowed and should have access to that token. (Which is what Dev Tools would allow you to access, but not <em>other people's</em> tokens.)</p>
<p>It becomes an issue when someone else can access that user's JWT, which is when things like using SSL/HTTPS show their value (because encryption prevents another user from sniffing traffic and retrieving the JWT, for example). This is a fairly broad topic to try and cover though, but ultimately if someone else can access some random user's JWT then there are security issues, yes. It's not strictly related, but I enjoy <a href="https://auth0.com/blog/cookies-vs-tokens-definitive-guide/" rel="nofollow">this Auth0 article</a> which talks about the differences between JWTs and cookies (which you may already understand -- and hence it may useful/interesting) and some of the related security concerns and how JWTs fit in to the picture.</p>
<blockquote>
<p>I could try and reduce the expiry date, however... isn't it true that as long as the user details are the same, the token generated will also be the same every time? So what's the point of the expiry date, if you are going to end up with the same token anyway?</p>
</blockquote>
<p>The token's expiry is stored within the body of the token (under a <code>exp</code> key), hence the token's value does change whenever a new token is generated with a different expiry time. RFC7519 states <code>the "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim.</code>, hence if the library you're using is acting correctly in this regard, then a token with an <code>exp</code> value in the past won't validate correctly and hence the token is unusable.</p>
|
How to get the key value output from RDD in pyspark <p>Following is the RDD:</p>
<pre><code>[(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']),
(4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])]
</code></pre>
<p>How do i print the keys and the value length for the above.</p>
<p>The output for above should be:
(key, no of words in the list) </p>
<blockquote>
<p>(8,1) (2,4) (4,8)</p>
</blockquote>
| <p>You can use a <code>map</code> function to create a tuple of the key and number of words in the list:</p>
<pre><code>data = sc.parallelize([(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']), (4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])])
data.map(lambda x:tuple([x[0],len(x[1])])).collect()
</code></pre>
|
Add custom Markers that will be shown in the Goto Symbol (Cmd+R) window <p>I've posted this exact same question in the ST forum plugin dev threads</p>
<p><a href="https://forum.sublimetext.com/t/add-custom-markers-that-will-be-shown-in-the-goto-symbol-cmd-r-window/23772" rel="nofollow">https://forum.sublimetext.com/t/add-custom-markers-that-will-be-shown-in-the-goto-symbol-cmd-r-window/23772</a></p>
<p>I've been using ST for a couple of years,</p>
<p>I'd like some guidance in first knowing if want I want to accomplish is possible through a plugin development, and if the answer is positive, maybe some reference as to where to start looking to develop this feature.</p>
<p>I would like to include some kind of marker that when placed in code, it includes a new entry in the list that is displayed in the Goto Symbol (Cmd+R) window. The closest example I have now is from Xcode, where in the source code you can include a comment with the "MARK:" keyword and it will render a new section in the top header bar of the editor (which is the equivalent of the goto symbol in ST).</p>
<p>When working with large files this feature would be of tremendous help because it allows to organize the blocks of code based on custom criteria regarding the logical relationships around it and not just the sequence of functions that exist in the file.</p>
| <p>The contents of the symbol list is controlled by a preferences file that tells sublime what scopes should appear in the symbol list for any given language and, optionally, what transformations should be done for display purposes (e.g. to indent the methods in a class). </p>
<p>Such configuration files are <code>tmPreferences</code> files (XML files in Plist format) within a package and which are generally named with names that start with <code>Symbol List</code>. For example, <code>Packages/C++/Symbol List.tmPreferences</code> is one of such files for use in the C++ package (which covers, C, C++ and both flavors of Objective-C). Since the files are Plist files the actual names don't matter, but this is a convention that makes such files easier to find.</p>
<p>There is some <a href="http://docs.sublimetext.info/en/latest/reference/symbols.html" rel="nofollow">documentation on symbols</a> you can read for more information.</p>
<p>Trivially, if you save the following XML into <code>Packages/C++/Symbol List Pragma.tmPreferences</code> it will add all of the <code>#pragma MARK</code> lines in your source files to the symbol list (current file only), replacing <code>#pragma MARK</code> with <code>" ---- "</code>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>name</key>
<string>Symbol List</string>
<key>scope</key>
<string>(source.c | source.c++ | source.objc | source.objc++) &amp; (meta.preprocessor.c)</string>
<key>settings</key>
<dict>
<key>showInSymbolList</key>
<integer>1</integer>
<key>showInIndexedSymbolList</key>
<integer>0</integer>
<key>symbolTransformation</key>
<string>
s/#pragma MARK/ ---- /g;
</string>
</dict>
</dict>
</plist>
</code></pre>
<p>This doesn't get you all the way there; for one thing, <code>#ifdef</code> and <code>#endif</code> directives are caught with this rule. Additionally it doesn't visually indent everything that follows which IIRC XCode does. However, it's a good starting point for seeing what is going on.</p>
<p>If you wanted to actually do this with special single line comments and not a <code>#pragma</code> I believe you would need to enhance the syntax highlighting for the language(s) you're targetting to match such comments and give them a scope that you can uniquely target.</p>
|
Finding median for given range of indices of an array <p>Given an array of integers, we have to answer certain queries where each query has 2 integers. These 2 integers are the 2 indices of the given array and we have to find the median of the numbers present between the 2 indices (inclusive of the given indices.)</p>
<p>Well sorting the array for each query is the most basic solution. Can this be solved with the help of segment trees or range queries?</p>
| <p>Here's how to do this in Python:</p>
<p>import numpy as np</p>
<pre><code>def median(arr):
arr_sort = sorted(arr)
n = len(arr)
n_over_two = int(n/2)
if (n%2 == 0):
return (arr_sort[n_over_two-1]+arr_sort[n_over_two])/2.0
else:
return arr_sort[n_over_two]
tmp = [5,4,3,2,1]
print(median(tmp))
tmp = [2,10,2,10,7]
print(median(tmp))
tmp = [4, 3, 2, 1]
print(median(tmp))
</code></pre>
<p>This works for any array. Taking median of a subset of an array just involves standard indexing of that array in python (inclusive of lower index, exclusive of upper - if you want inclusive of upper, add one):</p>
<pre><code>anArray=[0,0,0,1,2,3,4,10,10,10,10]
print(anArray[3:7])
print(median(anArray[3:7]))
</code></pre>
|
Maximum area of triangle having all vertices of different color <p>Points from (0,0) to (R,C) in the cartesian plane are colored r, g or b. Make a triangle using these points such that-</p>
<pre><code>a) All three vertices are of different colors.
b) At least one side of triangle is parallel to either of the axes.
c) Area of the triangle is maximum possible.
</code></pre>
<p>Output the maximum possible area.
Constraints : <code>1<=R<=1000</code> , <code>1<=C<=1000</code></p>
<p>Can someone please let me know the approach to this question?</p>
| <p>The area of a triangle is <code>1/2 * base * height</code>. So if one side of the triangle is parallel to the<br>
x-axis, then the base of the triangle is formed by two colors on the same row (spread as far apart as possible), and the third color should be on the row that's farthest from the base. Hence, you can preprocess the data to find:</p>
<ol>
<li>the top-most and bottom-most row for each color</li>
<li>the left-most and right-most column for each color on every row </li>
</ol>
<p>Then for every row, you have twelve possibilities for forming a triangle, e.g. </p>
<pre><code>left-most-red, right-most-blue, top-most green
left-most-red, right-most-blue, bottom-most green
left-most-red, right-most-green, top-most blue
...
</code></pre>
<p>And of course, there's the corresponding process for triangles with one edge parallel to the y-axis.</p>
<p>Thus, the problem can be solved in <em><code>O(R*C)</code></em> time, where most of the time is spent in the preprocessing. </p>
|
Dropwizard client deal with self signed certificate <p>Quite new with Dropwizard.</p>
<p>I found a lot of solution to deal with Jersey and ssl self signed certificate.
Dropwizard version is 0.9.2</p>
<p>I have tried to set a SSLContext but I get</p>
<pre><code>The method sslContext(SSLContext) is undefined for the type JerseyClientBuilder
</code></pre>
<p>Code:</p>
<pre><code> TrustManager[] certs = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
public static class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
private Client getWebClient(AppConfiguration configuration, Environment env) {
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
Client client = new JerseyClientBuilder(env)
.using(configuration.getJerseyClient())
.sslContext(ctx)
.build("MyClient");
return client;
}
</code></pre>
<p>The configuration part:</p>
<pre><code>private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration();
public JerseyClientConfiguration getJerseyClient() {
return jerseyClient;
}
</code></pre>
| <p>I think to create an insecure client in 0.9.2 you would use a Registry of ConnectionSocketFactory, something like... </p>
<pre><code> final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
final SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.INSTANCE)
.build();
builder.using(registry);
Client client = new JerseyClientBuilder(env)
.using(configuration.getJerseyClient())
.using(registry)
.build("MyInsecureClient");
</code></pre>
|
Excel IF function for three conditions (2 x number, 1 x text) and two outcomes <p>I have a column which has positive numbers, negative numbers and a text statement "No Responses.". If the number is positive I would like "yes" to be the outcome in a new column, if it is negative or the text 'No Responses." I would like the outcome to be "no" in a new column. I have tried the following:</p>
<pre><code>=IF(E2<0, "no", IF(E2="No Responses.", "no", "yes"))
</code></pre>
<p>However, I still get "yes" for "No Responses.". Does anyone have a solution. </p>
| <p>You could use the following to avoid any string comparison issues</p>
<pre><code>=IF(ISNUMBER(E2), IF(E2>0, "yes", "no"), "no")
</code></pre>
<p>This way only positive numbers will give a "yes" anything else is "no"</p>
|
How to create a Text type field in db via Hibernate+Java <p>I do have a Java Web Applicaiton (struts2, hibernate, beans) + PostreSQL as DB. The task is to save the <code>base64</code> encoded text in the db for some specific table. That <code>base64</code> is generated from <code>pdf</code> file, which is then <code>ciphered</code> with a specific algorithm. The <code>pdf</code> files <1mb, mostly <300kb. </p>
<p>I did a search and it's suggested to save the base64 as a <code>Text</code> field in the DB. It's not problem to create it within the PostgreSQL itself, but I have to create it via a <code>Model</code> class + hibernate.</p>
<p>What I did:</p>
<p>Imported <code>import org.apache.struts2.components.Text;</code></p>
<p>Generated getters/setters. Added one row to my <code>*.hbm.xml</code> file.</p>
<pre><code><property name="base64signed" column="base64signed" />
</code></pre>
<p>And I got this error:</p>
<blockquote>
<p>Could not determine type for: org.apache.struts2.components.Text</p>
</blockquote>
| <p>I think you should go with this annotation :</p>
<pre><code>@Lob(type = LobType.CLOB)
</code></pre>
|
Successor Arithmetic Prolog Mod function <p>How to write <strong>mod/3</strong> function for <strong>successor arithmetic</strong> (Peano's Numbers) in prolog?</p>
| <pre><code>s(0).
s(X):- X.
plus(0, Y, Y).
plus(s(X), Y, s(Z)):- plus(X , Y , Z).
minus(A, B, C) :- plus(C, B, A).
mod(_, 0, 0).
mod(0, _ , 0).
mod(X, s(0), 0).
mod(A, B, N) :- minus(A, B, R), (R @< B -> N = R ; mod(R, B, N)).
</code></pre>
|
Replace numbers in a file name in unix (BASH) <p>I have multiple files approximately 150 and there names do not match a requirement of a vendor. example file names are:</p>
<pre><code>company_red001.p12
company_red002.p12
.
.
.
.
company_red150.p12
</code></pre>
<p>I need to rename all files so that 24 is added to each number sequentially and that there are no preceding zero's and that the company_ component is removed.</p>
<pre><code>red25.p12
red26.p12
red27.p12
.
.
.
red150.p12
</code></pre>
<p>I have used a <em>for</em> loop in bash to remove the <em>company_</em> component but would like something that executes all changes simultaneously as I have to perform this at a moments notice.</p>
<p>example:</p>
<pre><code>#!/bin/bash
n = 24
for file in company_red*
do
new_name=$file$n
n=$(($+1))
mv -i $file $new_name
done
</code></pre>
<p>example 2</p>
<pre><code>#!/bin/bash
for f in company_red*
do mv "$f" "${f/company_red/red}";
done
</code></pre>
| <p>Do:</p>
<pre><code>for file in *.p12; do
name=${file#*_} ## Extracts the portion after `_` from filename, save as variable "name"
pre=${name%.*} ## Extracts the portion before extension, save as "pre"
num=${pre##*[[:alpha:]]} ## Extracts number from variable "pre"
pre=${pre%%[0-9]*} ## Extracts the alphabetic portion from variable "pre"
suf=${name##*.} ## Extracts the extension from variable "name"
echo mv -i "$file" "${pre}""$(printf '%d' $((10#$num+24)))"."${suf}" ## Doing arithmetic expansion for addition, and necessary formatting to get desired name
done
</code></pre>
<p>Outputs:</p>
<pre><code>mv -i company_red001.p12 red25.p12
mv -i company_red002.p12 red26.p12
</code></pre>
<p>The above is dry-run, remove <code>echo</code> if you are satisfied with the renaming to be done:</p>
<pre><code>for file in *.p12; do
name=${file#*_}
pre=${name%.*}
num=${pre##*[[:alpha:]]}
pre=${pre%%[0-9]*}
suf=${name##*.}
mv -i "$file" "${pre}""$(printf '%d' $((10#$num+24)))"."${suf}"
done
</code></pre>
|
Emoji not visible when copied from one table to another in Mysql <p>I have text with emojis in a sql table. Collation is set to utf8mb4_bin. The mobile app reads the emoji from table and displays correctly. It inserts the emojis properly.</p>
<p>Using dashboard, sometimes I copy this text to another table with same column and collation. But emoji from this table is not visible in mobile app. I see only ????????</p>
<p>Why so?</p>
| <p>Question Marks (regular ones, not black diamonds) (Se?or for Señor):</p>
<ul>
<li>The bytes to be stored are not encoded as utf8/utf8mb4. Fix this.</li>
<li>The column in the database is CHARACTER SET utf8 (or utf8mb4). Fix this.</li>
<li>Also, check that the connection during reading is UTF-8.</li>
</ul>
<p>More discussion: <a href="http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored">Trouble with utf8 characters; what I see is not what I stored</a></p>
|
Get data in Async Task in Android <p>I want to receive data inside <code>AsyncTask</code> class, a <code>list</code> sent as parameter from other class. I am unable to receive list in he <code>Async</code> class. Thanks in advance.</p>
<pre><code> classforAsync classforAsyncO = new classforAsync();
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(myList);
System.out.println("Going");
classforAsync(myList).execute();
}
});
</code></pre>
<p><strong>Async Class</strong></p>
<pre><code>public class classforAsync extends AsyncTask<String,Void,Void>{
private String[] list;
String str1,str2;
public classforAsync (String[] list ) {
this.list = list;
this.str1 = list[0];
this.str2 = list[1];
}
@Override
protected Void doInBackground(String... params) {
System.out.println("IN ");
System.out.println(str1);
System.out.println(str2);
return null;
}
}
</code></pre>
| <p>Try this. You must have a constructor in place to pass in your list. Update the <code>type</code> accordingly. </p>
<pre><code>public class classforAsync extends AsyncTask<String,Void,Void>{
private List<String> list;
public classforAsync(List<String> list) {
this.list = list;
}
@Override
protected Void doInBackground(String... params) {
System.out.println("IN ");
String str1 = list.get(0);
String str2 = list.get(1);
System.out.println(str1);
System.out.println(str2);
return null;
}
}
</code></pre>
<p>And you pass in the list like this</p>
<blockquote>
<p>new classforAsync(myList).execute();</p>
</blockquote>
|
Xamarin: How to get current theme name in code? <p>In Xamarin Android, how do I get the current theme name programmatically? I need to get the name as a string such as "Theme.AppCompat.Light.Dialog".</p>
| <p>You may refer to the code bellow:</p>
<pre><code>PackageInfo packageInfo;
packageInfo = PackageManager.GetPackageInfo(PackageName,PackageInfoFlags.MetaData);
int themeResId = packageInfo.ApplicationInfo.Theme;
var name = Theme.Resources.GetResourceEntryName(themeResId);
</code></pre>
<p>And here is the <a href="http://stackoverflow.com/questions/10302853/android-theme-name-from-theme-id">reference</a> about how to get theme name in Android project(using java)</p>
|
Search Bar showing wrong/mixed cell results <p>I have a problem in my iOS project. I'm using a search bar to filter my array in my custom tableview to show the matching keywords of the search. </p>
<p>It shows no code errors but obviously there's a problem.</p>
<p>Normally there's over 20+ items in my tableview but when I search, it only shows the first cell that my tableview normally has without searching, the same image for that cell to be exact, but it is not the same cell because each cell has a button showing specific information through a label in that cell. So when I search and a result comes out, it shows the image that the first cell in the tableview has but with the label or info of the correct cell or that matching cell has.</p>
<p>I don't know what it could be. Maybe it's keeping the image of the first cell because it's a custom tableview cell and for some reason it's not filtering out to the correct image. But the weird part that it's the correct cell that is showing because the specific label that each cell has is showing and not the label that the first cell has with the first cell's picture. I hope I'm making sense.</p>
<p><strong>Code:</strong></p>
<p><strong>numberOfRowsInSection</strong></p>
<pre><code>if (isFiltered) {
return [filteredGamesArray count];
}
return [gamesArray count];
</code></pre>
<p><strong>cellForRowAtIndexPath</strong></p>
<pre><code>Game * gameObject;
if (!isFiltered) {
gameObject = [gamesArray objectAtIndex:indexPath.row];
}
else {
gameObject = [filteredGamesArray objectAtIndex:indexPath.row];
}
return cell;
</code></pre>
<p><strong>searchBar textDidChange</strong></p>
<pre><code>if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
filteredGamesArray = [[NSMutableArray alloc] init];
for (Game *game in gamesArray) {
NSString *str = game.gameName;
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
[filteredGamesArray addObject:game];
}
}
}
[myTableView reloadData];
</code></pre>
<p>Also, I don't keep any images or text in my app. I get all the info that populates the tableview cell from a server using json/php/mysql, with images I use a URL.</p>
<p>I'm missing something here. If you need more details please let me know.</p>
<p><strong>cellForRowAtIndexPath</strong></p>
<pre><code>// Loading Images
NSURL * imgURL = [[gamesArray objectAtIndex:indexPath.row] valueForKey:@"gameURL"];
[cell.myImageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"no-image.jpg"] options:SDWebImageRefreshCached];
</code></pre>
| <p>Use NSPredicate for searching best option.</p>
<pre><code>searchArray=[[NSArray alloc]init];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.YOURSEARCHKEY contains[c] %@", YOURTEXTFIELD.text];
NSLog(@"%@",resultPredicate);
searchArray = [ORIGNALARRAY filteredArrayUsingPredicate:resultPredicate];
NSLog(@"%@",searchArray);
[self.colorTableview reloadData];
</code></pre>
<p>// Here check if searching is on or off and just update your array like</p>
<pre><code>if searching{
NSURL * imgURL = [[searchArray objectAtIndex:indexPath.row] valueForKey:@"gameURL"];
[cell.myImageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"no-image.jpg"] options:SDWebImageRefreshCached];
}else{
NSURL * imgURL = [[gamesArray objectAtIndex:indexPath.row] valueForKey:@"gameURL"];
[cell.myImageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"no-image.jpg"] options:SDWebImageRefreshCached];
}
</code></pre>
|
AJAX calls inside a loop <p>So, I have a list of data that I am out putting onto my view, and each list item has an id. </p>
<p>Each of these list items is a bar and I have a document created for each bar that at least one user is going to. For those bars where no users are going, there is no document created. </p>
<p>I need to make an AJAX call for each list item to the database to check</p>
<p>i) If a document exists for that list item
ii) If a document exists, how many users are going according to the document. </p>
<p>I attempted a solution using a while loop, where the update for the while loop was contained in the callback for the AJAX call. Here is the code</p>
<pre><code>function updateAllGoingButtons(){
var i = 0;
var dataToPass = {};
var numButtons = global_data_object.listData.businesses.length;
while(i < numButtons){
dataToPass.button = global_data_object.listData.businesses[i].id;
dataToPass = JSON.stringify(dataToPass);
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', '/update-buttons', dataToPass, function(data){
console.log(i);
i++;
}));
}
}
</code></pre>
<p>When I attempted to run the function, I got the error, </p>
<blockquote>
<p>Request entity too large</p>
</blockquote>
<p>So, is there a better way to go about doing what I am trying to do? Should I use promises? Or is there simply an error in the way I am trying to make the AJAX call from within a while loop? </p>
<p>For reference, here is the ajaxRequest function</p>
<pre><code>'use strict';
var appUrl = window.location.origin;
var ajaxFunctions = {
ready: function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
},
ajaxRequest: function ajaxRequest (method, url, data, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.setRequestHeader('Content-type', 'application/json');
xmlhttp.send(data);
}
};
</code></pre>
| <p>You should check out the npm library called async, it has an each method that you can do asynchronous calls within. If you use promises, the Promise.all method in Bluebird could be very useful for you.</p>
|
concatenating maptype values while doing groupby on dataframe <p>I have this dataframe which contains 3 columns -> userId, date, generation</p>
<pre><code>+-------+--------+----------------------------------------------------------------------------+
|userId | date |generation |
+-------+--------+----------------------------------------------------------------------------+
|1 |20160926|Map("screen_WiFi" -> 15.127, "upload_WiFi" -> 0.603, "total_WiFi" -> 19.551)|
|1 |20160926|Map("screen_2g" -> 0.573, "upload_2g" -> 0.466, "total_2g" -> 1.419) |
|1 |20160926|Map("screen_3g" -> 10.084, "upload_3g" -> 80.515, "total_3g" -> 175.435) |
+-------+--------+----------------------------------------------------------------------------+
</code></pre>
<p>I want to group these values on the basis of <strong><em>userId</em></strong> and <strong><em>date</em></strong>
but the problem is with the 3rd column which contains value of maptype and the requirement is to combine all the maptype values in one column, final output should look like this-><br>
<br></p>
<pre><code>+-------+--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|userId |date |generation |
+-------+--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|1 |20160926|Map("screen_WiFi" -> 15.127, "upload_WiFi" -> 0.603, "total_WiFi" -> 19.551,"screen_2g" -> 0.573, "upload_2g" -> 0.466, "total_2g" -> 1.419, "screen_3g" -> 10.084, "upload_3g" -> 80.515, "total_3g" -> 175.435)|
+-------+--------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code></pre>
<p>Is there any way to solve this problem , or any possible workaround??</p>
| <p>You can create a naive User Defined Aggregation Function (UDAF) that combines maps, and then use it as the aggregation function. Since you didn't define how to combine two <em>values</em> in the map for two <em>identical</em> keys, I will assume that keys are unique, i.e. for each <code>userId</code> and <code>date</code>, no key would appear in two different records:</p>
<pre><code>/***
* UDAF combining maps, overriding any duplicate key with "latest" value
* @param keyType DataType of Map key
* @param valueType DataType of Value key
* @tparam K key type
* @tparam V value type
*/
class CombineMaps[K, V](keyType: DataType, valueType: DataType) extends UserDefinedAggregateFunction {
override def inputSchema: StructType = new StructType().add("map", dataType)
override def bufferSchema: StructType = inputSchema
override def dataType: DataType = MapType(keyType, valueType)
override def deterministic: Boolean = true
override def initialize(buffer: MutableAggregationBuffer): Unit = buffer.update(0 , Map[K, V]())
// naive implementation - assuming keys won't repeat, otherwise later value for key overrides earlier one
override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
val before = buffer.getAs[Map[K, V]](0)
val toAdd = input.getAs[Map[K, V]](0)
val result = before ++ toAdd
buffer.update(0, result)
}
override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = update(buffer1, buffer2)
override def evaluate(buffer: Row): Any = buffer.getAs[Map[String, Int]](0)
}
// instantiate a CombineMaps with the relevant types:
val combineMaps = new CombineMaps[String, Double](StringType, DoubleType)
// groupBy and aggregate
val result = input.groupBy("userId", "date").agg(combineMaps(col("generation")))
</code></pre>
|
How to get last 90 days monday to sunday date? <p>How to get last 90 days monday to sunday date.</p>
<pre><code>S.no Start_dt End_dt week
1 18-Jul-16 24-Jul-16 Week1
2 25-Jul-16 31-Jul-16 Week2
3 1-Aug-16 7-Aug-16 Week3
4 8-Aug-16 14-Aug-16 Week4
5 15-Aug-16 21-Aug-16 Week5
6 22-Aug-16 28-Aug-16 Week6
7 29-Aug-16 4-Sep-16 Week7
8 5-Sep-16 11-Sep-16 Week8
9 12-Sep-16 18-Sep-16 Week9
10 19-Sep-16 25-Sep-16 Week10
11 26-Sep-16 2-Oct-16 Week11
12 3-Oct-16 9-Oct-16 Week12
13 10-Oct-16 16-Oct-16 Week13
</code></pre>
<p>We need to use sysdate as input.
I am trying below query it return current week monday ,sunday date</p>
<blockquote>
<p>SELECT TRUNC(sysdate, 'D') +1 startofweek, TRUNC(sysdate, 'D') + 7
endofweek FROM dual;</p>
</blockquote>
| <pre><code>select trunc(sysdate-(13-rownum)*7, 'iw') start_dt, trunc(sysdate-(12-rownum)*7, 'iw')-1 end_dt, 'week'||rownum week
from dual
connect by rownum<=90/7+1
</code></pre>
|
Passing pipe | and caret ^ chars through batch CALL <p>I'm trying to pass through caret chars through batch.
Escaping them once would be easy, but I need to do it twice.
I have an executable that will back up tables based on a Regex expression (not my code).
I want to back up all tables with an exclusion list.
Using <code>^(?!tableName$).*</code> works for a single table.</p>
<p>Batch File 1 (called from command line)</p>
<pre><code>SET ignoreTables=tableName
:: Call the backup script
CALL SecondBatch.bat %ignoreTables%
</code></pre>
<p>Batch File 2</p>
<pre><code>:: Passthrough ignoreTables
Executable.exe --ignoreTablesPattern="^(?!%1$).*"
</code></pre>
<p>But I'd like to ignore multiple tables. In Regex this means using the | (pipe) character eg; <code>tableOne|tableTwo</code> would require;</p>
<p><code>SET ignoreTables=tableOne^|tableTwo</code></p>
<p>Which is correct at the <code>SET</code> but not when passed to the <code>CALL</code></p>
<p>The correct output that works from the command line is;</p>
<pre><code>Executable.exe --ignoreTablesPattern="^(?!tableOne|tableTwo$).*"
</code></pre>
<p>How can I get this result out of the batch file?</p>
| <p>In batch file 1 use:</p>
<pre><code>SET "ignoreTables=tableOne|tableTwo"
:: Call the backup script
CALL SecondBatch.bat "%ignoreTables%"
</code></pre>
<p>And in batch file 2 use:</p>
<pre><code>:: Passthrough ignoreTables
Executable.exe --ignoreTablesPattern="^(?!%~1).*$"
</code></pre>
<p>Run in a command prompt window <code>cmd /?</code> and read the output help pages, especially the last paragraph on last help page which is about when surrounding a directory/file name or parameter string with double quotes is required.</p>
<p>The first line of batch file 1 contains the command <strong>SET</strong> with the parameter string <code>variable=value</code>. By enclosing this parameter string in double quotes the pipe character is not interpreted anymore as operator. For more details about using double quotes on assigning a string to an environment variable see answer on <a href="http://stackoverflow.com/a/26388460/3074564">Why is no string output with 'echo %var%' after using 'set var = text' on command line?</a></p>
<p>The value of the environment variable is passed next expanded as first parameter to batch file 2. Again surrounding double quotes are needed to pass the string containing <code>|</code> as literal string to the second batch file.</p>
<p>In the second batch file it is necessary to reference the first argument without surrounding quotes. Therefore <code>%~1</code> is used now instead of <code>%1</code> as explained in help of command <strong>CALL</strong> output on running in a command prompt window <code>call /?</code>.</p>
<p>BTW: I'm quite sure <code>$</code> should be at end of the regular expression and not inside the negative lookahead.</p>
|
Android, What is the difference between neenbedankt A.P and Support Annotation? <p>Recently I replaced <code>neenbedankt</code> annotation processing library with google <code>Support-Annotation</code> library, and change all <code>apt</code> methods in <code>build.gradle</code> with <code>annotationProcessor</code> and every thing works good, My question is what is the difference between them and when should we use each of them?</p>
| <p>There is no difference. <code>annotationProcessor</code> is the new feature of gradle plugin.</p>
<p>More info from the creator of <code>android-apt</code> <a href="http://www.littlerobots.nl/blog/Whats-next-for-android-apt/" rel="nofollow">here</a></p>
<p>The main conclusion from this article is that <code>annotationProcessor</code> is doing the same as <code>android-apt</code> and that is why <code>android-apt</code> is no longer maintained. You are advised to use <code>annotationProcessor</code></p>
|
ng-repeat angularjs conflicting whit ng-model <p>i am creating a web app in which i am using angularjs for database conectivity</p>
<p>here is my code</p>
<pre><code><div ng-repeat="x in sonvinrpm">
<input type="Text" ng-model="venuemobile" value="{{x.venuemobile}}" ng-init="venuemobile='{{venuemobile}}'"
</div>
<button ng-click="updfunction()">update</button>
</code></pre>
<p>on my page load my textbox fetching particular venuemobile from my database(<code>1234567890</code>) if i edit the venuemobile and press update the value of venuemobile should be updated</p>
<p>but i am facing the error</p>
<pre><code> missing parameter: venuemobile
</code></pre>
<p>and i found out this error is appearing because i am using repeater,</p>
<p>when i remove repeater and enter into textbox manually then my database is updating properly, </p>
<p>previously i used ng-repeater for my dropdownlist and table(<code>because there are multiple data not single data</code>) in this case i need only one value from database, what should i use instead of <code>ng-repeat</code></p>
| <p>You do not have to call a function to update a $scope variable, since angular uses two way data binding by default, the updated value will be bound to scope. Anyway your HTML should be</p>
<pre><code><input type="Text" ng-model="venuemobile" value="{{venuemobile}}" ng-init="venuemobile='{{venuemobile}}'"
</div>
</code></pre>
|
Mac Mini - Continuous Integration <p>Does anyone here leverage Mac Mini Server with continuous integration?</p>
<p>I am currently facing an issue where vendor is trying to use the company's mini server for continuous integration but both of them are having different Apple ID, of course none of the provisioning profile will be match. In this case, even the vendor has submitted the code to repo but will Mac Mini be able to run, test and sign on the app?</p>
<p>How would the xCode know switching the app from one team to another? (Both are different Apple ID, Team, Provisioning Profile.. etc)</p>
| <p>The way I typically handle this is by giving each machine its own Apple ID. Then you can invite that Apple ID to any developer team you need and give it its own dev certificate/key. Make sure they have the appropriate provisioning profiles downloaded as well.</p>
|
How to declare collection name and model name in mongoose <p>I have 3 kind of records,</p>
<pre><code>1)Categories,
2)Topics and
3)Articles
</code></pre>
<p>In my mongodb, i have only 1 colection named 'categories' in which i stroe the above 3 types of documents.</p>
<p>For these 3 modules,i wrote 3 models(one each) in such a way like below,</p>
<pre><code>mongoose.model('categories', CategorySchema);
mongoose.model('categories', TopicSchema)
mongoose.model('categories', ArticlesSchema)
</code></pre>
<p>like....mongoose.model('collection_name', Schema_name)</p>
<p>but when i run my code ,it throws error that </p>
<pre><code>Cannot overwrite `categories` model once compiled.
</code></pre>
<p>If i change the above models like this,</p>
<pre><code>mongoose.model('category','categories', CategorySchema);
mongoose.model('topics','categories', TopicSchema)
mongoose.model('articles','categories', ArticlesSchema)
</code></pre>
<p>It is creating 2 collections named topics and articles which i dont want.
This is my issue right now,can anyone suggest me help.....Thanks....</p>
| <p>Try-</p>
<pre><code>mongoose.model('category', CategorySchema, 'categories');
mongoose.model('topics', TopicSchema, 'categories');
mongoose.model('articles', ArticlesSchema, 'categories');
</code></pre>
<p>As mentioned in docs: <a href="http://mongoosejs.com/docs/api.html#index_Mongoose-model" rel="nofollow">http://mongoosejs.com/docs/api.html#index_Mongoose-model</a></p>
<blockquote>
<p>Mongoose#model(name, [schema], [collection], [skipInit])</p>
<p>Defines a model or retrieves it.</p>
<p>Parameters:</p>
<ul>
<li>1st param - name <String> model name</li>
<li>2nd param - [schema] <Schema> schema name</li>
<li>3rd param - [collection] <String> collection name (optional, induced from model name)</li>
<li>4th param - [skipInit] <Boolean> whether to skip initialization (defaults to false)</li>
</ul>
</blockquote>
<p>See - <a href="http://stackoverflow.com/a/14454102/3896066">http://stackoverflow.com/a/14454102/3896066</a></p>
|
up a telephone number in the directory with Android <p>I want a function that allows Clicking a button on my application, the directory is opened and when the user selects a contact, its number is copied in a EditText on my program. as with the buttons ("+") found on messaging applications.</p>
| <p>Your button clicklistener will look like</p>
<pre><code>BUTTON.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts with phone numbers
startActivityForResult(pickContactIntent, 100);
}
});
</code></pre>
<p>And in your onActivityResult will be like,</p>
<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if (requestCode==100) {
Uri contactUri = data.getData();
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String mobile = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() +]", "");
EDITTEXT.setText(mobile);
}
}
}
}
</code></pre>
|
How do I pass in an argument to a list of lambdas? <p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p>
<pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}
</code></pre>
<p>This is what I have so far, but I don't know how to pass in an argument to a list of lambda expression which act as the filter for each dictionary in the list.</p>
<pre><code>sample_dict = [
{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'},
{'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'},
{'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'},
{'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'},
{'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'}
]
def get_matched_lines(input_dict, **param):
filters = [lambda input_dict_elem,
input_key=param_key,
input_value=param_value:
input_dict_elem[input_key] == input_value
for param_key, param_value in param.items()]
return [dict_elem for dict_elem in input_dict if(all(filters))]
print(get_matched_lines(sample_dict, a='woot', e='1', c='duh'))
</code></pre>
| <p>You can do this (in Python 2.7):</p>
<pre><code>def get_matched_lines(input_dict, **param):
return [dic for dic in input_dict if all([key in dic and dic[key] == val for key, val in param.iteritems()])]
</code></pre>
<p>The same code in Python 3 is</p>
<pre><code>def get_matched_lines(input_dict, **param):
return [dic for dic in input_dict if all([key in dic and dic[key] == val for key, val in param.items()])]
</code></pre>
|
How to take year 2016 onwards? <p>I have this code below working fine w/o the condition in the line <code>payrollEndDate = p.PayrollEndDate.Value.Year >= 2016</code> because it gives me an error <code>Invalid cast from 'Boolean' to 'DateTime'.</code> and the code that I added is return a boolean</p>
<pre><code>var per = (from p in db.Periods select new { periodId = p.PeriodId, periodStart = p.StartDate, periodEnd = p.EndDate, payrollEndDate = p.PayrollEndDate.Value.Year >= 2016 });
var periods = (from p in per.AsEnumerable() select new { perId = p.periodId, PayrollEndDate = Convert.ToDateTime(p.payrollEndDate).ToShortDateString() }).AsQueryable();
ViewBag.PeriodEndDate = new SelectList(periods, "PayrollEndDate", "PayrollEndDate", null);
</code></pre>
<p>How to take the year 2016 onwards?</p>
| <p><code>select</code> is for projections, not filtering. It sounds like you want a <code>where</code> clause instead. I'd suggest not using query expressions here, given that you're only doing simple things:</p>
<pre><code>var query = db.Periods
.Where(p => p.PayrollEndDate != null &&
p.PayrollEndDate.Value.Year >= 2016)
.AsEnumerable()
.Select(p => new {
p.PeriodId,
PayrollEndDate = p.PayrollEndDate.Value.ToShortDateString()
});
</code></pre>
<p>(I strongly suspect you don't actually want the <code>AsQueryable()</code> call there... it may give the <em>impression</em> that any further querying will be done in the database, but that would be an illusion, given that you've got <code>AsEnumerable()</code> already.)</p>
<p>I've removed the <code>Convert.ToDateTime</code> call as I'm assuming <code>p.PayrollEndDate.Value</code> is already a <code>DateTime</code>.</p>
|
How to search over whole cities in combobox <p>I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox. </p>
<pre><code>string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
</code></pre>
| <p>You could change the statement in case of "nothing selected"</p>
<pre><code>if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
</code></pre>
<p>Remarks:</p>
<ul>
<li>use variable names like <code>string sCity = "%";</code> instead of <code>string c = "%";</code></li>
<li>use parameters for your sql statements <code>where ( PER_ID = @Person)</code> and <code>cmd.Parameters.Add("@Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);</code></li>
</ul>
|
Regarding Docusign envelope API <p>I am getting the below response using <code>Docusign</code> envelope API</p>
<pre><code>{
""envelopeId"": ""0aac02c3-ccdc-4bfe-88af-eefa2438d696"",
""uri"": ""/envelopes/0aac02c3-ccdc-4bfe-88af-eefa2438d696"",
""statusDateTime"": ""2016-10-14T10:39:02.4900000Z"",
""status"": ""created""
}
</code></pre>
<p>I am unable to open the envelope, even though I have logged into the <code>Docusign</code> site in the web. Let me know the URL to open the envelope. The response doesn't give the exact URL.</p>
| <p>Created status means you will find it in your draft folder and that it has not been sent. If you want a <a href="https://www.docusign.com/p/RESTAPIGuide/Content/REST%20API%20References/Post%20Sender%20View.htm" rel="nofollow">POST sender view</a> then you will need to make the correct call and use the URL returned by DocuSign to access the view and send the envelope. </p>
|
How to add an unspecified amount of variables together? <p>I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use <code>list</code>. I can't figure out how I'm supposed to add each new variable together without a <code>list</code>. When I run the code it adds the last entered <code>price1</code> which is <code>-1</code>. I need to use the <code>-1</code> to tell the program to total all the variables. </p>
<pre><code>count = 0
while (True):
price1 = int( input("Enter the price of item, or enter -1 to get total: "))
count += 1
if (price1 ==-1):
subtotal = (price1 + ) #this is where I"m having trouble
#at least I think this is the problem
tax = (subtotal*0.05)
total = (subtotal + tax)
print("Subtotal: . . . . . ", subtotal)
print("Tax: . . . . . . . . ", tax)
print("Total: . . . . . . . .", total)
break
</code></pre>
| <p>Keep another variable around and sum than up, also, <code>count</code> isn't used for anything so no real reason to keep it around. </p>
<p>For example, initialize a <code>price</code> name to <code>0</code>:</p>
<pre><code>price = 0
</code></pre>
<p>then, check if the value is <code>-1</code> and, if not, simply increment (<code>+=</code>) the <code>price</code> variable with the value obtained for <code>price1</code>:</p>
<pre><code>if price1 == -1:
subtotal = price
tax = subtotal*0.05
total = subtotal + tax
print("Subtotal: . . . . . ", subtotal)
print("Tax: . . . . . . . . ", tax)
print("Total: . . . . . . . .", total)
break
else:
price += price1
</code></pre>
|
Run method in parallel in C# and collate results <p>I have a method that returns a object. In my parent function I have a list of IDs.</p>
<p>I would like to call the method for each ID I have and then have the objects added to a list. Right now I have written a loop that calls the method passing each ID and waits for the returned object and then goes to the next ID.</p>
<p>Can this be done in parallel? Any help here would be most helpful.</p>
| <p>I think <strong>Task parallel libraries</strong> will help you</p>
<pre><code>Task[] tasks = new Task[2];
tasks[0] = Task.Factory.StartNew(() => YourFunction());
tasks[1] = Task.Factory.StartNew(() => YourFunction());
Task.WaitAll(tasks);// here it will wait untill all the functions get completed
</code></pre>
|
Gantt chart in cakephp <p>I need Gantt chart in cakephp.I have tried Some Jquery Gantt charts .</p>
<p>But for my requirement i found 'dhtmlxGantt' is suitable.
But it works fine for only limited number of tasks.</p>
<p>Is there any solution for this.or any alternative charts ??Kindly suggest.</p>
| <p>Try RadiantQ jQuery Gantt - www.radiantq.com. Support unlimited number of tasks through virtualization.</p>
|
Kafka - mirror from one server to another server <p>I'm trying to mirror Kafka real-time data from one server to another server.</p>
<p>Found a tool called 'Mirror Maker' at Apache website.</p>
<p>[Apache Kafka Mirror Maker][1]
<a href="https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27846330#Kafkamirroring(MirrorMaker)-Howtosetupamirror" rel="nofollow">https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27846330#Kafkamirroring(MirrorMaker)-Howtosetupamirror</a></p>
<p>But the description is too simple, without configuration detail of consumer.config & producer.config files.</p>
<p>How to deploy this tool with correct config files for mirroring data between two Kafka servers for:</p>
<ol>
<li><p>Real-time topics transfer</p></li>
<li><p>fault-tolerant under unstable network</p></li>
</ol>
<p>Any other possible way to achieve this is also very welcome.</p>
<p>Thanks.</p>
| <p>Apache's Mirror Maker is a relatively simple tool, this is why all the documentation you read doesn't seem incredible informative. There isn't much information to give. All it does is produce data from cluster A and consume to cluster B. Mirror Maker does provide real-time topic transfer but as far as stability goes you may need to look to third party tools such as <a href="https://eng.uber.com/ureplicator/" rel="nofollow">https://eng.uber.com/ureplicator/</a>. </p>
|
Working process of logical NOT operator in if(!(i%6)) <pre><code>#include<stdio.h>
int main(void)
{
int i;
char ch;
/*display all numbers that are multiples of 6*/
for(i=1; i<10000; i++){
if(!(i%6)){
printf("%d, more?(Y/N)", i);
ch= getche();
if(ch=='N')break; /* stop the loop*/
printf("\n");
}
}
return 0;
}
</code></pre>
<p>Aim of program: Program will print multiple of 6. And a key press can stop the execution of the program.</p>
<p>How program works: In for loop, system will check value of i against the given condition. If the value of i is smaller than 10000, statements under for will be executed.
The first statement under for loop is a if statement. When the condition of if statement is true, all the statements under if will be executed. Again, when the condition becomes false, all statements will skipped.</p>
<p>For example: when i = 6, system will check against the condition in for. It is true 6 is smaller than 100000. Next if statement will start execution. If if statement becomes true then value of i will print by the system.</p>
<p>My question: What is exactly the meaning of the condition in if(!(i%6))? How it's check whether value of i is multiple of 6 or not?</p>
<p>Thank you in advance.</p>
| <p>Actually it is not quite clear what is your question / what exactly you dont understand. However, I will try to clarify:</p>
<pre><code>if(!(i%6)){
</code></pre>
<p>First <code>(i%6)</code> is evaluated, then you should consider that the not operator takes a <code>bool</code> as parameter:</p>
<pre><code>bool operator!(bool)
</code></pre>
<p>If a <code>int</code> is converted to <code>bool</code> then <code>0</code> becomes <code>false</code>, while everything else becomes <code>true</code>. Thus the above could equivalently be written as:</p>
<pre><code>if(!(i%6 != 0)){
</code></pre>
<p>or a bit less obfuscated:</p>
<pre><code>if(0==(i%6)){ // or if ((i%6)==0){
</code></pre>
|
If i<1000,this program can run successfully ,but i change it to i<10000, this program can't run ,Why this happened? <p>Something test about Java GC</p>
<pre><code>public class StringTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1;
for(int i=0;i<10000;i++){
s1="1";
System.out.print(s1);
}
}
}
</code></pre>
| <p>This is an issue of your console (assumed Eclipse). Your program is running, and the output is shown, but for whatever reason the console can not properly handle lines of that length. In practice, it is seldom required to print such long lines. You should consider using <code>System.err.println()</code> instead of <code>System.err.print()</code> so that each iteration of your loop is printed on its own line.</p>
<p>However, you can also solve the issue by modifying the console settings in Eclipse:</p>
<p><a href="https://i.stack.imgur.com/bw7f0.png" rel="nofollow"><img src="https://i.stack.imgur.com/bw7f0.png" alt="Eclipse screen shot"></a></p>
<p>By specifying a <strong>fixed width console</strong>, your output is properly shown (as it is wrapped at the specified console width).</p>
|
How to find the Indices of a pixel label using a loop <p>I have this segmented image in which I need to find the indices of all pixels labelled â20â
I know I can easily do this with the code:</p>
<pre><code>img = [00 00 00 00 00 00 00 00;
00 20 00 00 00 20 00 00;
00 00 30 00 00 00 00 00;
10 10 10 00 20 00 00 00;
10 10 10 40 40 40 40 40;
10 10 10 40 40 40 20 40;
10 10 10 40 40 40 40 40];
[img_row, img_col] = find(img==20)
imgIdx = sub2ind(size(img), img_row, img_col);
</code></pre>
<p>This will return a vector of all the indices of the pixels of interest. However, I would rather want to find these pixels one after the other, and I know that:</p>
<pre><code>imgIdx = find(img==20, 1)
</code></pre>
<p>will return the index for the 1st of these pixels. Thus, is there a way to find the rest of these pixels using a loop? Any help/suggestion/advice is duly appreciated. Many thanks.</p>
| <p>Of course, it is not efficient to loop through an image with typically 10's of thousands to millions of elements. But if you insist, there is always a loop solution.</p>
<pre><code>for ii = 1:numel(img)
if img(ii) == 20
% do_the_thing
end
end
</code></pre>
<p>Nevertheless, even if I have to loop over <code>% do_the_thing</code>, I will do it after getting all the indices:</p>
<pre><code>imgIdx = find(img == 20);
for ii = 1:numel(imgIdx)
% imgIdx(ii) !!!
% do_the_thing
end
</code></pre>
|
JDBC Phoenix driver for HBASE, retries 36 and throws exception <p>I have a standalone HBase installed in a server(Remote).
I written a Java Client, which communicates using Phoenix, and saw it tries for 36 attempts and hence throws exception.<br></p>
<pre><code>HBase-Version : 1.1.5
Phoenix-core: 4.8.0-HBase-1.1
</code></pre>
<p>ConnectionString:</p>
<pre><code>Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
Connection connection = DriverManager.getConnection("jdbc:phoenix:192.168.1.xxx:2181");
</code></pre>
<p>Am I missing somethinghere, cz its not connecting at all.</p>
<p>Exception:</p>
<pre><code>Exception in thread "main" java.sql.SQLException: org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=36, exceptions:
Mon Oct 17 11:50:18 IST 2016, null, java.net.SocketTimeoutException: callTimeout=60000, callDuration=80992: row 'SYSTEM:CATALOG,,' on table 'hbase:meta' at region=hbase:meta,,1.1588230740, hostname=HOSTNAME,16201,1476683863488, seqNum=0
</code></pre>
<p>Can some one help me out..!</p>
| <p>In my experience, this usually occurs when you're getting timeouts on the scanners. And in your case, that appears to be true, as well b/c in your error message it says:</p>
<blockquote>
<p>callTimeout=60000, callDuration=80992</p>
</blockquote>
<p>meaning you went on for 81 seconds when your timeout was a minute. When querying HBase, you want to make sure you're using the rowkey or in newer versions of phoenix, the timestamp as well. Any other HBase query is going to be ridiculously inefficient. You can try a few things:</p>
<ol>
<li>Try setting your HBase timeout to a ridiculously high number like 4 hours</li>
<li><p>Again, change your query to use the existing rowkey. In one table we have, the first character of the rowkey is 0-9 so we'll run the following:</p>
<pre><code>select * from TABLE WHERE ROWKEY like '0%' AND [other_conditions]
select * from TABLE WHERE ROWKEY like '1%' AND [other_conditions]
etc...
</code></pre>
<p>And then combine the results or if we're counting, just multiply by 10 b/c that's usually good enough for our purposes</p></li>
<li><p>Finally, you may have to write a better rowkey to optimize for your phoenix queries. This is more of an advanced topic, but it's true of all HBase querying. HBase is good at one thing and that's querying its one, powerful index: the rowkey. Using phoenix doesn't alleviate that issue.</p></li>
</ol>
<p>And by the way, from a stack overflow standpoint, it helps if you post a little about your query and your table structure.</p>
|
javascript function is not working in cakephp <p>I have casecading in zone , state and city. I have added following code in my Controller and View. but my Javascript function <code>onchange</code> is not working in View form, please help </p>
<p>Code for controller:</p>
<pre><code><?php
class StatesController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$zones = $this->{$this->modelClass}->Zone->find("list", array('conditions' => array('is_active' => 1)));
$this->set(compact('zones'));
//allow actions
$this->Auth->allow(array('get_states'));
}
public function add() {
parent::add();
$this->loadModel('Zone');
//Renders the common form for add and edit actions
$this->render('form');
}
* Get States. list According to zone_id by ajax call
*/
function get_states() {
$this->autoRender = false;
$zone_id = 0;
if (!empty($_POST['zone'])) {
$zone_id = $_POST['zone'];
}
$states = $this->State->find('list', array(
'conditions' => array(
'zone_id' => $zone_id,
'is_active' => ACTIVE
),
'order' => array('name' => 'asc')
));
$states = array_flip($states);
echo json_encode($states);
}
}`
code for view
<code>
<aside class="body_rt">
<!--Page head start-->
<div class="page_head">
<h1> <?php echo ucwords($model); ?> Manager</h1>
<div class="back">
<?php echo $this->Html->link($this->Html->image('images/back.png'), array(
'action' => 'index'), array('escape' => false, 'title' => "Back"));
?>
</div>
</div>
<!--Page head end-->
<!--Message head start-->
<?php if (($this->Session->check('Message.failure'))) { ?>
<section class="bolg_warp custom_message">
<div class="sub_head">Message</div>
<div class="flashMessage failure-flash">
<?php echo $this->Session->flash('failure'); ?>
</div>
</section>
<?php } ?>
<!--Message head end-->
<!--Blog warp start-->
<section class="bolg_warp">
<?php echo $this->Form->create($model, array('type' => 'file',
'inputDefaults' => array( 'label' => false, 'div' => false ))); ?>
<div class="three_column">
<ul>
<li>
<?php echo $this->Form->hidden('id', array('class' => 'text_field')); ?>
</li>
<li>
<h2>Outlet Code:</h2>
<h3>
<?php echo $this->Form->input('outlet_code', array('class' => 'text_field')); ?>
</h3>
</li>
<li>
<h2>Name: <span class ="required">*</span></h2>
<h3>
<?php echo $this->Form->input('name', array(
'class' => 'text_field')); ?>
</h3>
</li>
<li>
<h2>Zone :</h2>
<h3>
<?php echo $this->Form->input('zone_id', array(
'options' => $zones,
'label' => false,
'div' => false,
'value' => '',
'class' => 'text_field short_field',
'empty' => 'All'
));
?>
</h3>
</li>
<li>
<h2>State :</h2>
<h3>
<?php echo $this->Form->input('state_id', array(
'options' => $states,
'label' => false,
'div' => false,
'value' => '',
'class' => 'text_field short_field',
'empty' => 'All'
));
?>
</h3>
</li>
<li>
<h2>Status: </h2>
<h3>
<?php echo $this->Form->input("is_active", array("type" => "checkbox",
"class" => "form-control checkbox")) ?>
</h3>
</li>
</ul>
</div>
<div class="centerbutton">
<ul>
<li>
<?php echo $this->Form->submit('images/save.png' , array('class'=>'ajax-submit')); ?>
</li>
<li>
<?php
echo $this->Html->link($this->Html->image('images/cancle.png'), array('controller' => $controller, 'action' => 'index'),
array('escape' => false));
?>
</li>
</ul>
</div>
<?php echo $this->Form->end(); ?>
</section>
<!--Blog warp end-->
</aside>
<!--cascding -->
<script>
$(function(){
var domain = "http://" + document.domain;
$("select#CityZoneId").on('change', function () {
var zone_id = $(this).val();
if (zone_id != '')
{
var url = domain + "/states/get_states";
$.post(url, {zone: zone_id}, function (data) {
var obj = $.parseJSON(data);
$("#CityStateId option").remove();
$("#CityStateId").append("<option value=''>All</option>")
$.each(obj, function (i, value) {
$("#CityStateId").append("<option value='" + value + "'>" + i + "</option>")
});
});
}
});
});
</script>
</code></pre>
<p></p>
<p>please tell me where i am doing wrong</p>
| <p>you seem to not call the same id as in your input, try changing your jQuery to this:</p>
<p><code>$("#zone_id").on('change', function () {
//your stuff
}</code></p>
|
react+redux how can son component get props? <p>this is my code:<br>
<strong>action:</strong><br>
<code>const increaseAction = { type: 'increase' }</code><br>
<strong>reducer:</strong> </p>
<pre><code> // Reducer
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
â case 'increase':
â â return { count: count + 1 }
â default:
â â return state
}
}
</code></pre>
<p>this is my Store:<br>
<code>const store = createStore(counter)</code><br>
<strong>and others:</strong> </p>
<pre><code> // Map Redux state to component props
function mapStateToProps(state) {
console.log(33333);
return {
â value: state.count
}
}
// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
â onIncreaseClick: () => {
â â console.log(22222222222);
â â dispatch(increaseAction)
â }
}
}
// Connected Component
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Main)
ReactDOM.render(
â <Provider store={store}>
â â <App />
â </Provider>,
document.getElementById('content')
);
</code></pre>
<p>**My Main component: ** </p>
<pre><code>>>class Main extends React.Component {
constructor(props) {
â super(props);
}
render() {
const {value, onIncreaseClick} = this.props;
â return (
â â <div className={reactRootClass}>
â â â <div className='trade-left' onClick={onIncreaseClick}>
â â â </div>
â â â <div className='trade-right'>
â â â â <Counter />
â â â </div>
â â </div>
â )
}
}
</code></pre>
<p>and this is my question:<br>
now, I can call <code>onIncreaseClick</code> on <code><div className='trade-left' onClick={onIncreaseClick}></code></p>
<p>now I want call <code>onIncreaseClick</code> in my <code><Counter /></code> component, how can I get <code>value</code> and <code>onIncreaseClick</code> like in <code><Main></code> component? with <code>props</code>?<br>
and this is my <code><Counter></code> component: </p>
<pre><code>>>import React, { Component, PropTypes } from 'react'
export default class Counter extends Component {
render() {
â const { value, onIncreaseClick } = this.props
â return (
â â <div>
â â â <span>{value}</span>
â â â <button onClick={onIncreaseClick}>Increase</button>
â â </div>
â )
}
}
</code></pre>
<p>I just want to call <code>onIncreaseClick</code> in this</p>
| <p>You can pass down peice of state (to children's) via MapStateToProps method ,similarly you can pass down actions to children's via mapDispatchToProps function like below : </p>
<pre><code>function mapDispatchToProps(dispatch) {
const {updateData} = importedActions;
return {
actions: bindActionCreators({updateData}, dispatch),
};
}
</code></pre>
<p>This the way containers communicated with all the children's component in hierarchy </p>
|
How to use promises in mongoose <p>By runnig the below code,i can see the values in my console,but the response i got is empty ,i thoink it may be because of promises....</p>
<p>My code,</p>
<pre><code>exports.getcatlist = function(req, res) {
var params = req.params,
item = {
'status': '1',
'type': 'categories'
};
Categories.find(item,function (err, result) {
if (err) {
return
}
if (result) {
var profiles = [];
var categories_to_get = []
var categories = []
for (var i in result) {
var id = result[i]._id;console.log(id)
var id = id.toString();
categories_to_get.push(get_category(id, profiles))
}
Promise.all(categories_to_get)
.then(() => {
console.log('final vals'+categories_to_get)
res.json({status: 'success', data: profiles});
})
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
})
function get_category(id, profiles) {
var profiles = [];
return new Promise(function (resolve, reject) {
var item = {
'categoryid' : id,
'status': '1',
'type': 'topics',
};
Categories.count(item,function (err, result) {
if (err) {
reject(err)
return
}
if (result == []) {
profiles.push(result)
resolve()
}
if (result) {
profiles.push(result)
resolve()
} else {
reject()
}
});
})
}
}
</code></pre>
<p>By runnig the above code,i can see the values in my console,but the response i got is empty </p>
<pre><code>`{
"status": "success",
"data": []
}`
</code></pre>
<p>I am not sure why i am getting my data as empty,can anyone please suggest help...</p>
| <p>Sorry but your code is pretty messy, here's solution and clean approach, i would strongly suggest to use <a href="http://caolan.github.io/async/" rel="nofollow"><code>async</code></a> library for things you tryin to accomplish.</p>
<pre><code>//npm install async --save
var async = require('async');
exports.getcatlist = (req, res) => {
var params = req.params;
Categories.find({
status: '1',
type: 'categories'
}, (err, result) => {
if(err)
return res.json({status: 'fail'});
var profiles = [];
async.each(result, (id, cb) => {
Categories.count({
categoryid: id,
status: '1',
type: 'topics'
}, (ierr, val) => {
if(ierr)
return cb(ierr);
profiles.push(val);
cb();
});
}, (eachError) => {
if(eachError)
return res.json({status: 'fail'});
res.json({status: 'success', data: profiles});
});
}
}
</code></pre>
|
Using the '.localhost' TLD searches in browsers instead of showing the site associated with the address <p>According to <a href="https://tools.ietf.org/html/rfc2606" rel="nofollow">RFC 2606 (1999)</a> the TLD <em>.localhost</em> is reserved for use for testing locally.</p>
<p>The goal is to configure a preview site to run locally using the TLD .localhost, e.g. <a href="http://example.localhost" rel="nofollow">http://example.localhost</a></p>
<p>The problem is that when I use Chrome or Safari to access a '.localhost' TLD it searches google for example.localhost instead of treating it as a proper address. This is after configuring the <em>hosts</em> file to point back to <code>127.0.0.1</code>.</p>
<p>Am I misunderstanding the usage of this reserved TLD? Is there a way to configure this to work properly?</p>
| <p><code>.localhost</code> is not an existing, delegated TLD, which is why your browser doesn't find it.</p>
<p>What RFC 2606 says is that <code>.localhost</code> (along with <code>.test</code>, <code>.invalid</code> and <code>.example</code>) will never be a delegated TLD, so you can safely use that name for your own, local, purposes. That is, if you want to set up a private TLD for internal use, that TLD can be safely named <code>.localhost</code> without the risk of a future collision with a globally assigned name.</p>
|
How to get height of UITableView when cells are dynamically sized? <p>I have a UITableView with cells that are dynamically sized. That means I have set:</p>
<pre><code>tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
</code></pre>
<p>Now I want to get the height of the whole table view. I tried getting it through <code>tableView.contentSize.height</code> but that only returns the estimated row height, and not the actual dynamic height of the table view.</p>
<p>How do I get the dynamic height of the whole table view?</p>
| <p>You should calculate the height of tableView in the following delegate method,</p>
<pre><code>func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//Get the height required for the TableView to show all cells
if indexPath.row() == (tableView.indexPathsForVisibleRows.last! as! NSIndexPath).row {
//End of loading all Visible cells
float heightRequiredForTable = tableView.contentSize.height
//If cell's are more than 10 or so that it could not fit on the tableView's visible area then you have to go for other way to check for last cell loaded
}
}
</code></pre>
|
Auto scroll with data updates <p>So I'm trying to make an info screen for a local company in my neighborhood. They want a page, that automatically scrolls to the bottom, then gets back to the top and reloads the data from some outlook calendars. I'm using ASP.net to do so, but I can't seem to figure out how to use javascript (jQuery) to make something automatically scroll to the bottom of the page and then back to the top to then reload the data.</p>
<p>That's where you guys come into the picture, I could really use some help here!
Just for knowledge, I'm not the best at javascript, so if you could explain what's happening in your answer, that would be lovely!</p>
<p>Regards.</p>
| <p>You can use <strong>Jquery Ajax</strong> for this query.</p>
<p>Here is <a href="http://www.codeproject.com/Articles/239436/Load-Data-From-Server-While-Scrolling-Using-JQuery" rel="nofollow">link</a>. It wiil help you</p>
|
Return single record from multi join with LINQ in form of viewmodel in MVC <p>I'm trying to return a single record from multi join by LINQ in MVC, I use a model from my personnel database that have main table named personnel, some fields are only an id and dependent on other tables.
Therefore, I need a way to join these tables to retrieve all data, filter them by an id Parameter and put LINQ result to a view model and return it to view.
This is my <a href="https://i.stack.imgur.com/k5bcO.png" rel="nofollow">Database Model</a>, I used the following code but it doesn't work.</p>
<pre><code>public ActionResult Details(int id)
{
var q = from personnel in db.Personels
join Genders in db.Genders on personnel.GenderId equals Genders.Id
join nationality in db.Nationalities on personnel.NationalityId equals nationality.Id
join religion in db.Religions on personnel.ReligionId equals religion.Id
join course in db.Courses on personnel.CourseId equals course.Id
join accBank in db.AccBanks on personnel.AccBankId equals accBank.Id
join advanceStatus in db.AdvanceStatus on personnel.AdvanceStatusId equals advanceStatus.Id
join chart in db.Charts on personnel.ChartId equals chart.Id
join contract in db.Contracts on personnel.ContractId equals contract.Id
join costCenter in db.CostCenters on personnel.CostCenterId equals costCenter.Id
join job in db.Jobs on personnel.JobId equals job.Id
join level in db.Levels on personnel.LevelId equals level.Id
join military in db.Militaries on personnel.MilitaryId equals military.Id
join subReligion in db.SubReligions on personnel.SubReligionId equals subReligion.Id
join taxTable in db.TaxTables on personnel.TaxTableId equals taxTable.Id
join unit in db.Units on personnel.UnitId equals unit.Id
join workHouse in db.WorkHouses on personnel.WorkHouseId equals workHouse.Id
join licence in db.Licences on personnel.LicenceId equals licence.Id
join payPlace in db.PayPlaces on personnel.PayPlaceId equals payPlace.Id
join married in db.MarriedStatus on personnel.MarriedId equals married.Id
join jobStatus in db.JobStatus on personnel.JobStatusId equals jobStatus.Id
where (personnel.Id == id)
select new PersonnelViewModel()
{
PersonelNo = personnel.PersonelNo,
PersonelFName = personnel.PersonelFName,
PersonelLName = personnel.PersonelLName,
FatherName = personnel.FatherName,
NId = personnel.NId,
RecognizeNo = personnel.RecognizeNo,
BirthDate = personnel.BirthDate,
BirthPlace = personnel.BirthPlace,
RecordCity = personnel.RecordCity,
WorkHouse = workHouse.Name,
CostCenter = costCenter.Name,
Course = course.Name,
Nationality = nationality.Title,
Licence = licence.Title,
Religion = religion.Title,
SubReligion = subReligion.Title,
Military = military.Title,
Level = level.Title,
Chart = chart.Name,
Job = job.Name,
PayPlace = payPlace.Title,
Unit = unit.Name,
Contract = contract.Title,
Gender = Genders.Title,
MarriedStatus = married.Title,
ChildQty = personnel.ChildQty,
InsNo = personnel.InsNo,
Address = personnel.Address,
PhoneNumber = personnel.PhoneNumber,
MobileNumber = personnel.MobileNumber,
Status = personnel.Status,
ProcessStatus = personnel.ProcessStatus,
JobStatus = jobStatus.title,
TaxPerFree = personnel.TaxPerFree,
TaxPriceFree = personnel.TaxPriceFree,
StartWorkDate = personnel.StartWorkDate,
StartRuleDate = personnel.StartRuleDate,
EndRuleDate = personnel.EndRuleDate,
StopWorkDate = personnel.StopWorkDate,
TimeYearlyPrice = personnel.TimeYearlyPrice,
DateYearlyPrice = personnel.DateYearlyPrice,
TaxMonth = personnel.TaxMonth,
AccBankNo = personnel.AccBankNo,
AccBank = accBank.Title,
SumTimeWork = personnel.SumTimeWork,
SumTaxPrice = personnel.SumTaxPrice,
SumPay = personnel.SumPay,
PrepareStatus = personnel.PrepareStatus,
TotalStandWork = personnel.TotalStandWork,
InsPerFree = personnel.InsPerFree,
InsPriceFree = personnel.InsPriceFree,
SumPerWork = personnel.SumPerWork,
SumPerWorkTemp = personnel.SumPerWorkTemp,
AccCode = personnel.AccCode,
PrnFish = personnel.PrnFish
};
return View(q);
}
</code></pre>
<p>Is there a way?</p>
| <p>You have two options here. You can use the <code>Single()</code> method. This will check the entire collection for a single instance that meets the predicate that you can supply or you can uses the <code>SingleOrDefault()</code>. If the collection does not have a instance that meets the predicates requirements then a default value will be returned instead. </p>
<p>The <code>Single()</code> and <code>SingleOrDefault()</code> methods will throw an exception if more than one record is found that meets the predicate requirement. If that is the case then you can use the <code>First()</code> method or the <code>FirstOrDefault()</code> method. These methods tend to execute quicker as well as because once an instance is found in your collection no further work is performed to test if any more instances exist. </p>
|
Adobe Air - Mobile Width and Height <p>I have written my first mobile AIR app. On my iPad, the layout is a dismal failure. It looks perfect in the Flash Builder simulator. </p>
<p>I have the application set up to run in portrait mode with no auto-orientation. It starts at 160 DPI and scales up. When the application is complete, I get the width and height of the stage, and then use these numbers to calculate the layout of all of my buttons and column widths for my datagrid. When I load the app on the iPad, all of the buttons are spread way too far apart, several running off the screen. The datagrid is all supposed to fit on the screen but four of the columns ran off the screen. </p>
<p>It is almost as if it calculated the width of the screen in landscape mode instead of in portrait mode. So I have two questions: </p>
<p>1) If you layout the application in portrait orientation, is the width of the stage the width in portrait orientation or landscape orientation? </p>
<p>2) I am confused on how to lay everything out on mobile devices with varying screen densities. Is it better to get the app width and height and then set up distances and spacing in pixels, or to use percentages? </p>
<p>Thanks for any insight. This was disappointing.</p>
<p><strong>Edit:</strong>
When the application is complete, I dispatch a custom event to let the rest of my components know that the app is loaded so that they can then get the width and height of the app and lay themselves out appropriately. In my main app, I have this code: </p>
<pre><code>protected function appCreationCompleteHandler(event:FlexEvent):void {
// Dispatch an event to the rest of the application that the application is complete so that I can calculate all of my layout distances
var e:Event = new Event("appComplete", true);
dispatchEvent(e);
appWidth = stage.stageWidth;
appHeight = stage.stageHeight;
}
</code></pre>
<p>In my application descriptor file, I have the following values set: </p>
<pre><code><aspectRatio>portrait</aspectRatio>
<autoOrients>false</autoOrients>
<fullScreen>true</fullScreen>
<visible>true</visible>
<softKeyboardBehavior>pan</softKeyboardBehavior>
</code></pre>
<p>I feel like it has to be something in my descriptor file, because it is laid out perfectly in the simulator, just not on the device. The height values appear to be correct on the device, but the width layout is just WAY off.</p>
| <p>The problem is probably that the screenWidth and screenHeight are still returning the real width and height but since you are setting the DPI to a fixed value the actual visible area is smaller than that ?</p>
<p>You could use the Capabilities.screenDPI to recalculate the real size but the problem is that it is highly unreliable on many devices (means it returns a wrong DPI).</p>
<p>Try to get the width and height with the Screen class:</p>
<pre><code>var screen:Screen = Screen.getScreensForRectangle(stage.nativeWindow.bounds)[0];
var width:int = screen.visibleBounds.width;
var height:int= screen.visibleBounds.height;
</code></pre>
|
I am New To the Development of Outlook Plugin Using C# I want to achieve the following design in my app <p><a href="https://i.stack.imgur.com/lWEe4.png" rel="nofollow"><img src="https://i.stack.imgur.com/lWEe4.png" alt="enter image description here"></a></p>
<p>I want to integrate the following specifications in my outlook Add-in like the highlighted area this should be implemented below the Message form as shown in the picture.Please suggest me some idea how i should start and should i use windows forms object or what?</p>
<p>some of my code </p>
<pre><code>public partial class ThisAddIn
{
Office.CommandBar newToolBar;
Office.CommandBarButton firstButton;
Office.CommandBarButton secondButton;
Office.CommandBarButton SettingsButton;
Office.CommandBarButton LogoutButton;
public static Outlook.Application OutlookObject = new Outlook.Application();
public static Outlook.NameSpace oNS = OutlookObject.GetNamespace("MAPI");
public static Outlook.MAPIFolder RootFolder;
public Outlook.Store NewPst = null;
string pathOnly = AppDomain.CurrentDomain.BaseDirectory;
Outlook.Explorers selectExplorers;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
selectExplorers = this.Application.Explorers;
selectExplorers.NewExplorer +=new Outlook .ExplorersEvents_NewExplorerEventHandler(newExplorer_Event);
AddToolbar();
CreateNewPST_Click();
}
}
</code></pre>
| <p>You can create a Task Pane (<a href="https://msdn.microsoft.com/en-us/library/aa942864.aspx?f=255&MSPPError=-2147217396" rel="nofollow">https://msdn.microsoft.com/en-us/library/aa942864.aspx?f=255&MSPPError=-2147217396</a>) or a Form Region (<a href="https://msdn.microsoft.com/en-us/library/bb386301.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/bb386301.aspx</a>).</p>
|
How can i merge more arrays in javascript <p>I have 3 or more array :</p>
<pre><code> var array1 = [a,b,c];
var array2 = [c,d];
var array3 = [e,f];
</code></pre>
<p>Want to get 1 merged array with the result like this one:</p>
<pre><code>result = [ace, acf, ade, adf, bce, bdf, bde, bdf, cce, ccf, cde, cdf]
</code></pre>
<p>How can i do it ,please note: array input will not limit.</p>
<p>Please help me, thank u so much.</p>
| <p>You could use an iterative and recursive approach with a combination algorithm.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function combine(array) {
function c(part, index) {
array[index].forEach(function (a) {
var p = part.concat([a]);
if (p.length === array.length) {
r.push(p.join(''));
return;
}
c(p, index + 1);
});
}
var r = [];
c([], 0);
return r;
}
console.log(combine([['a', 'b', 'c'], ['c', 'd'], ['e', 'f']]));
console.log(combine([['a', 'b', 'c'], ['d', 'e'], ['f', 'g'], ['h', 'i', 'j']]));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>
</div>
</div>
</p>
|
sizeForItemAtIndexPath not work with custom flowLayout? <p>I've replaced default <code>UICollectionViewFlowLayout</code> with my custom <strong>subclass</strong> of <code>UICollectionViewFlowLayout</code>, and I found that <code>sizeForItemAtIndexPath</code> didn't work any longer.
Did I miss something, or I should set <strong>itemSize</strong> in my custom flowLayout?</p>
| <p>In your subclass, use <code>itemSize</code> instead:</p>
<pre><code>- (CGSize)itemSize
{
return CGSizeMake(100,100);
}
</code></pre>
|
Need the default SSL certificate validation in iOS app <p>The iOS app needs the basic ssl validation to secure the client-server communication. I need a way to avoid SSL pinning which may have the client-server dependencies and need to update the app if the SSL cert changed. </p>
<p>Is there any way to allow all the valid SSL cert issued by any trusted CA's ?</p>
| <p>If you are looking for a way to bypass the transport security layer imposed by apple, you can do this.</p>
<p>Put the below code in your plist file</p>
<pre><code><key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</code></pre>
<p><strong>* This would disable the transport security layer and allow you to connect to insecure sources. Please beware that this is not recommended by apple and you should always use the TLS *</strong></p>
<p>Check out this link to understand apple's App Transport Security better. There might be some keys in this link that you can configure to achieve what you are looking for</p>
<p><a href="http://www.neglectedpotential.com/2015/06/working-with-apples-application-transport-security/" rel="nofollow">http://www.neglectedpotential.com/2015/06/working-with-apples-application-transport-security/</a></p>
|
Automatic Db migration (MysQl) <p>I'm doing a project in angular.js and node.js, which have three different environments(development, test and product).Each of them have different database(Mysql).My question is related to database migration,</p>
<p><strong>At present</strong> Db migration (from development to test/product) is doing in a way</p>
<ul>
<li>Compare two database by using db differentiation tools and create a sql file which contains the changes (queries) which needs to execute in to the other data base</li>
<li>Execute all the queries to the database (test/product) manually</li>
</ul>
<p><strong>What i Need:</strong></p>
<p>I would like to automate these Db migration(above mentioned process) by using any tools in a way</p>
<ul>
<li>needs to do the comparison of two databases(dev and product) and also save those changes in to a file and execute these changes in to the database (total Db synchronization) By running codes in command line prompt.</li>
</ul>
<p>i have read about <strong>flyway</strong> and <strong>knex</strong>. But dont know which tool can be used to achieve my requirements. </p>
<p>Can anyone suggest any free tools that can be used to automate the db migration process, Or any alternate process to achieve these requirements.</p>
| <p>You could try <a href="http://www.red-gate.com/products/mysql/mysql-compare/" rel="nofollow">MySQL Compare</a>. This is a commercial tool developed at the company I work for, but is free for non-commercial use.</p>
<p>This <a href="https://www.simple-talk.com/sql/sql-tools/mysql-compare-the-manual-that-time-forgot-part-1/" rel="nofollow">Simple Talk article</a> has more information, including how to automate using the command line. Good luck!</p>
|
Font-awesome Icon disappearing on change of font <p>I'm trying to incorporate <em>font-awesome</em> icons in my webpage, and it all works fine, until I change to my font of choice, <em>Exo 2</em>, and the icons show up as a bordered square. It works fine with other fonts, but for some reason this won't work.</p>
<p>I have included the <em>font-awesome</em> stylesheet, and the google fonts stylesheet.</p>
<p>If anyone could point me to what I'm doing wrong, would be appreciated!</p>
| <p>fontawesome is font icons and Exo 2 is font and not "font icons"</p>
<p>to work fontawesome u must apply</p>
<pre><code>font-family: FontAwesome;
</code></pre>
<p>and if u change it to something else here i think "Exo 2"</p>
<pre><code>font-family: Exo 2;
</code></pre>
<p>it wont work and will disply u square</p>
|
getRenditions() on org.apache.chemistry.opencmis.client.api.CmisObject returns null <p>I am using Apache Chemistry 0.14.0 to access documents in Alfresco 5.1. I am using AtomPub binding to access Alfresco.</p>
<p>When I invoke getRenditions() method on CmisDocument null is returned for all documents. Any ideas what could be the cause?</p>
| <p>By default, renditions are not requested. You have to use an OperationContext with a rendition filter.</p>
<p>See:</p>
<ul>
<li><a href="https://chemistry.apache.org/docs/cmis-samples/samples/content/index.html#working-with-renditions" rel="nofollow">https://chemistry.apache.org/docs/cmis-samples/samples/content/index.html#working-with-renditions</a></li>
<li><a href="https://chemistry.apache.org/docs/cmis-samples/samples/operation-context/index.html#rendition-filter" rel="nofollow">https://chemistry.apache.org/docs/cmis-samples/samples/operation-context/index.html#rendition-filter</a></li>
</ul>
|
why spark can not recovery from checkpoint by using getOrCreate <p>Following offical doc, I'm trying to revovery StreamingContext:</p>
<pre><code>def get_or_create_ssc():
cfg = SparkConf().setAppName('MyApp').setMaster('local[10]')
sc = SparkContext(conf=cfg)
ssc = StreamingContext(sparkContext=sc, batchDuration=2)
lines = ssc.socketTextStream('localhost', 9999).checkpoint(10)
def update_func(x, y):
return sum(x) + (y or 0)
word = lines.flatMap(lambda x: x.split()).map(lambda x: (x, 1)).updateStateByKey(update_func)
word.pprint()
return ssc
ssc = StreamingContext.getOrCreate('checkpoint', get_or_create_ssc)
ssc.start()
ssc.awaitTermination()
</code></pre>
<p>When I launch code at the first time(checkpoint is empty), It works as well</p>
<p>To simulate system failures, I turn off Terminal </p>
<p>But it can not recover when launching again</p>
<p>Terminal only show this</p>
<pre><code>16/10/17 15:04:53 WARN Utils: Your hostname, localhost resolves to a loopback address: 127.0.0.1; using 192.168.177.1 instead (on interface eth0)
16/10/17 15:04:53 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/10/17 15:04:55 WARN SparkContext: Use an existing SparkContext, some configuration may not take effect.
16/10/17 15:04:57 WARN SocketInputDStream: isTimeValid called with 1476686252000 ms whereas the last valid time is 1476686572000 ms
[Stage 3:> (0 + 0) / 20]
</code></pre>
<p>And there is no new information later </p>
| <p>Finally,I found the reason from Spark UI`s Environment page.</p>
<p>When I launch the code at first time, spark.master has been set to 'local[10]'ã</p>
<p>But after recover from checkpoint , spark.master change to 'local[*]' automatically </p>
<p>I have to edit conf/spark-defaults.conf with 'park.master local[10]' due to my VMware only has one core.</p>
<p>In offical doc there is a comment say that:</p>
<pre><code>Metadata includes:
Configuration - The configuration that was used to create the streaming application.
</code></pre>
<p>It seems that Configuration does not include spark.master.</p>
<p>Why ?</p>
|
Find max value of two tables, <p>Lets say we have 2 tables with number of cats and dogs respectively and name of cities. We want find in which city there are more cats than dog using a SQL statement.</p>
| <p>I think that the next query will do his work for you.</p>
<pre><code>SELECT cat.city_name
FROM (SELECT upper(city_name), count(*) quantity
from cats
group by upper(city_name)) cat
, (SELECT upper(city_name), count(*) quantity
from dogs
group by upper(city_name)) dog
where dog.city_name = cat.city_name
and cat.quantity > dog.quantity;
</code></pre>
|
align flex child at top-center and bottom-center, flexbox <p>I need a layout using flexbox, where 2 flex-items, item-1 should be aligned at top-center, while item-2 should be at bottom-center. I could not figure out how to do that.</p>
<p>See the below code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container{
padding:10px;
background: #fff;
border-radius:5px;
margin: 45px auto;
box-shadow: 0 1.5px 0 0 rgba(0,0,0,0,1.1);
}
.item{
color: #fff;
padding: 15px;
margin: 5px;
background: #3db5da;
border-radius: 3px;
}
.container{
display: flex;
min-height: 50vh;
justify-content: center;
align-items: center;
flex-direction: column;
}
.item{
/*margin: auto;*/
/*align-self: flex-start;*/
}
.item-4{
align-self: flex-start;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="item item-4">
Flex Item
<p>Vertical and horizontal align easy!</p>
</div>
<div class="item item-5"> bottom-center</div>
</div></code></pre>
</div>
</div>
</p>
<p>Here is fiddle link : <a href="https://jsfiddle.net/q5cw4xvy/" rel="nofollow">https://jsfiddle.net/q5cw4xvy/</a> </p>
| <p>Do you mean something like this?
<a href="https://jsfiddle.net/da4jdff7/1/" rel="nofollow">https://jsfiddle.net/da4jdff7/1/</a></p>
<pre><code>.container{
display: flex;
min-height: 50vh;
align-items: center;
flex-direction: column;
}
.item-5 {
margin-top: auto
}
</code></pre>
|
Convert textarea model to array <p>I am new to angularjs. I have textarea as below.</p>
<pre><code><textarea class="form-control" maxlength="100" ng-model="EmailList"></textarea>
</code></pre>
<p>The user enters data in the text box as a list in the textarea (as below).</p>
<pre><code>Data1
Data2
Data3
</code></pre>
<p>My model is also updated in the same way entered in the textarea, when checked with console.log(as below). </p>
<pre><code>Data1
Data2
Data3
</code></pre>
<p>I want to separate the each line value into an array. But I dont have any separator available to spilt the data. Can you please help me on this.</p>
<p>Thanks in Advance.</p>
| <p>Angular offers <a href="https://docs.angularjs.org/api/ng/directive/ngList" rel="nofollow">ngList</a> that does exactly that:</p>
<pre><code><textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
</code></pre>
<p>Every line will end up as entry the the array <code>list</code>.</p>
|
FindBy in pageFactory (webdriver) doesn't work correctly <p>I want to write tests in selenium <code>WebDriver</code> with <code>PageFactory</code>, but if I add annotations in <code>PageFactory</code> form in class</p>
<pre><code>@FindBy(id="email")
public WebElement mailLink;
</code></pre>
<p>and usage:</p>
<pre><code>mailLink.sendKeys("mail@mail.com");
</code></pre>
<p>I get a <code>NullPointerException</code> every time. Another way:</p>
<pre><code>driver.findElement(By.id("email")).sendKeys("mail@mail.com");
</code></pre>
<p>returns correct value. Where is the problem with first method?</p>
<p>My code:</p>
<p>I have got driver initialization in FaceClass:</p>
<pre><code>public class FaceClass {
protected WebDriver driver;
public FaceClass(WebDriver driver){
this.driver = driver;
}
public HomePage navigateToApp(){
driver.navigate().to("https://facebook.pl");
return PageFactory.initElements(driver, HomePage.class);
}
</code></pre>
<p>}</p>
<p>and class with business logic:</p>
<pre><code>public class HomePage extends FaceClass{
public HomePage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
@FindBy(id="email")
public WebElement mailLink;
@FindBy(id="pass")
public WebElement passLink;
@FindBy(how = How.ID, using="u_0_n")
public WebElement loginButton;
public ProfilePage navigateToProfile(){
try{
if(driver.findElement(By.id("pass")).isEnabled() || driver.findElement(By.id("pass")).isDisplayed()){
System.out.println("ok!");
}
//driver.findElement(By.id("pass")).sendKeys("pass_to_account");
//driver.findElement(By.id("email")).sendKeys("mail@mail.com");
//driver.findElement(By.id("u_0_n")).click();
mailLink.sendKeys("mail@mail.com");
passLink.sendKeys("pass_to_account");
loginButton.click();
} catch (Exception e) {
e.printStackTrace();
}
return PageFactory.initElements(driver, ProfilePage.class);
}
</code></pre>
<p>}</p>
<p>and test:</p>
<pre><code> public class ExampleTest {
WebDriver driver;
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability("marionette", true);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("https://facebook.pl");
}
@After
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void test() {
//fail("Not yet implemented");
HomePage homepage = new HomePage(driver);
homepage.navigateToProfile();
}
</code></pre>
<p>}</p>
<p>All elements are enabled and visible</p>
| <p>You did not initialize your elements before using. To initialize your page elements PageFactory method initElements. It's better if you call it in your constructor like this:</p>
<pre><code>public HomePage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
</code></pre>
<p>Hope it works.</p>
|
Non https web sites display the content of https sites <p>We have a cpanel server that hosts some web sites. we have 2 hosts that use SSL. When I open a non SSL website with http:// everything is ok but when I type https:// , it shows the contents of one of the SSL websites instead of displaying not found error!!
Usually the first one which is defined in httpd.conf.
I also signed up in cPanel forum, but I do not know how to post a new question!! I cannot find post a question or new post or something like that.</p>
<p>Any help is appreciated.</p>
| <p>Your question is really confusing. It would be better if you can edit and elaborate your question. Still let me guess your question and answer it.</p>
<p>Your cPanel server has hosted more than one websites, out of them only two have SSL certificate. Let me guess those two sites as abc.com and xyz.com. Now if I have understood your question properly, when you try to access 123.com (which is non HTTPS website) with HTTPS it is showing content of abc.com.</p>
<p>If yes, then this case refers to SSL misconfiguration. To solve this issue, SSL certificate should be installed properly on both websites and only those two sites can be accessible with HTTPS. It is advisable to use SSL Certificate checker for both sites to know whether SSL is installed properly or not.</p>
|
how to store data that is receieved to webserver from arduino <p>Since i didnt do any webserver code so far,my mind is full of questions.Lets say I have web server and I want to store data that comes from an arduino in database.How can I receive data ? Do I have to use php,write a script for webserver.Lets say I write the script and I made server to listen the port,where should I put script in my server in order to make server listen the port all the time.I need a tutorial.Any help will be appreciated.
Thanks in advance.</p>
| <p>I already did something like you want to do, and today I think the best choice is to do a <a href="http://stackoverflow.com/questions/671118/what-exactly-is-restful-programming">REST api</a> on an external webserver (you can do it with PHP). You can also install you API (or any other kind of program) on your arduino but you will be limited by the memory (depending the amount of data you write).</p>
|
How to play a single frequency tone on android device? <p>I'm new in android development. I'm now trying to play a single tone on a specific frequency on my cell phone. I didn't find any method that could play a specific tone. For example, only play a tone on 400Hz.
Does anyone help me to find some method? Thank you.</p>
<p>PS:Some friends mentioned me that this question is same with another question. But after I test that code I got three frequencies.<a href="https://i.stack.imgur.com/rgNQq.jpg" rel="nofollow">here is the spectrum I got from that question</a></p>
| <p>There are a utility software under linux named 'sox' which can generate any single frequency you wanted.
for example:
sox -r 44100 -n 5.wav synth 60 sine 20<br>
this command can generate a file named 5.wav, which is 20Hz sine wave with sample rate 44.1k and lasting 60 seconds.
you can try android version:
<a href="https://github.com/Kyborg2011/SoxPlaye" rel="nofollow">https://github.com/Kyborg2011/SoxPlaye</a></p>
|
No key with alias found in keystore <p>Our android project consists of <strong>mobile and wear app</strong> ( wear app is under development) and we are trying to release the mobile app. When we try to generate signed apk we get this follow message : </p>
<pre><code>Error:Execution failed for task ':wear:packageRelease'.
> com.android.ide.common.signing.KeytoolException: Failed to read key
toyanathpatro from store "/home/adventure/toyanath_patro_key/toyanath_patro_key":
No key with alias 'toyanathpatro' found in keystore /home/adventure/toyanath_patro_key/toyanath_patro_key
</code></pre>
<p>As it reads it says failed task for <strong>:wear:packageRelease</strong> where in reality we are selecting just the mobile while choosing for signing the apk. </p>
<p>Can anyone point out my blunder ? Thanks in advance. </p>
| <p>In your build.gradle you have defined a signing config that it's pointing to a keystore that it's not in your code base.</p>
<p>Something similar to this.</p>
<pre><code>android {
...
buildTypes {
release {
signingConfig signingConfigs.staging
...
}
}
signingConfigs {
defaultSignature {
keyAlias 'default'
keyPassword 'password'
storeFile file('default-keystore.jks')
storePassword 'password'
}
}
}
</code></pre>
|
Incrementing The Index getting error <p>I am using the <code>core data</code> in my Project. I have an option to add the car in my App and i am displaying that added cars inside the <code>tableView</code> fortunatly i have added 3 rows. When I open my App I am calling the Service in that I am getting totally 45 data. I have to compare that 3 <code>tableview</code> data with the 45 data. </p>
<p>Here I created an <code>NSInteger</code> totalCars variable. </p>
<p>Here is my code:</p>
<pre><code>totCars = self.carSelectionManager.totalCars;
</code></pre>
<p>and I am getting the first row data by passing the âindex = 0â statically.</p>
<pre><code>Car *car = [self.carSelectionManager carAtIndex:0];
[self.service getMakesForYear:car.year]; // with the help of first row data I am calling the service data.
</code></pre>
<p>I am getting the first row data. Similarly I want the remaining second and third row data too. But I am unable to write the logic for that can anyone help to solve this issue.</p>
<p>Thanks In Advance.</p>
| <p>Please try :</p>
<pre><code>for ( Car * car in self.carSelectionManager){
[self.service getMakesForYear:car.year];
}
</code></pre>
<p>Or you can try this:</p>
<pre><code>if (carSelectionManager){
for ( int i = 0 ; i < [self.carSelectionManager count];i++){
Car *car = [self.carSelectionManager carAtIndex:0];
[self.service getMakesForYear:car.year];
}
}
</code></pre>
|
DirectoryInfo.GetFiles throws unhandled StackOverflowException <p>In my Downloading document Application I am getting the <code>Stackoverflow Exception as Unhandled</code> when I am iterating through the Directory to get the files details and renaming & moving the files to some folder my code is</p>
<pre><code>public FileInfo GetNewestFile()
{
try
{
System.IO.DirectoryInfo directory = new DirectoryInfo(TempDownloadFolder);
FileInfo result = null;
var list = directory.GetFiles(); // Stackoverflow Exception occurs here
if (list.Count() > 0)
{
result = list.OrderByDescending(f => f.LastWriteTime).First();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
</code></pre>
<p>i.e The application downloads the <code>PDF</code> and <code>MS-Word</code> Files from a website if it downloads <code>PDF</code> file sequentially the <code>directory.GetFiles()</code> works fine, but when it downloads 1 or more <code>PDF</code> file and then downloads a <code>MS-Word</code> file the application throws <code>System.Stackoverflow</code> Exception.</p>
<p>When I restart the application downloads the <code>MS-Word</code> file as its is the first file in the lineup it works well only until another MS-Word` file comes up for download after few files have been downloaded </p>
<p>As far as my knowledge the Exception may be occurring because of huge memory allocated but I cannot figure out why its not happening for <code>PDF</code> file but only happening for <code>MS-Word</code> file </p>
<p><strong>Edit:</strong></p>
<p>The previous code I had used to return newest file was</p>
<pre><code>return di.GetFiles()
.Union(di.GetDirectories().Select(d => GetNewestFile()))
.OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
.FirstOrDefault();
</code></pre>
<p>the above code also resulted in Stackoverflow exception</p>
| <p>Please try <code>directory.EnumerateFiles()</code> instead of <code>directory.GetFiles()</code>. Then also, instead of <code>.Count() > 0</code> use <code>.Any()</code>.</p>
<p>They differ as follows:</p>
<ul>
<li>When you use <code>EnumerateFiles</code>, you can start enumerating the collection of FileInfo objects before the whole collection is returned.</li>
<li>When you use <code>GetFiles</code>, you must wait for the whole array of FileInfo objects to be returned before you can access the array.
Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.</li>
</ul>
<p>From this MSDN page: <a href="https://msdn.microsoft.com/en-us/library/4cyf24ss(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/4cyf24ss(v=vs.110).aspx</a></p>
|
Separate system of coordinates for x and y <p>I am using matplotlib for plotting in my project. I have a time series on my chart and I would like to add a text annotation. However I would like it to be floating like this: x dimension of the text would be bound to data (e.g. certain date on x-axis like 2015-05-04) and y dimension bound to Axes coordinates system (e.g. top of the Axes object). Could you please help me accomplish something like this?</p>
| <p>It seems like I found the solution: one should use blended transformation:
<a href="http://matplotlib.org/users/transforms_tutorial.html#blended-transformations" rel="nofollow">http://matplotlib.org/users/transforms_tutorial.html#blended-transformations</a></p>
|
How to set PHPExcel_Cell_DataType::TYPE_STRING in krajee yii2-export <p>I meet a problem - when I export excel by Krajee yii2-export it will change long number to scientific notation in which lost last two bits.
For example 201210171530 will be 2.012E+12, when I click it, 2.012E+12 will display as 201210171500. The last two bit '30' is lost,because '30' change to be '00'</p>
<p>How can I fix it? Or where can I set the cell datatype?<br>
<img src="https://i.stack.imgur.com/FRp4f.png" alt="enter image description here"></p>
| <p>when your export successfull, you must open your excel
and then you block the number metric and then, right click the block
choose Format Data, and then click Number, and OK</p>
|
Javascript condition not working as expected <p>I have a JS code which works fine when </p>
<pre><code>checkQueryString != "M"
</code></pre>
<p>but When the value becomes <code>checkQueryString == "M"</code> it doesn't goes inside the loop </p>
<p>Here is my code.</p>
<pre><code>function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
if(checkQueryString == "M")
{
alert('Value is M now');
}
else {
alert('Kindly select the stage');
}
}
}
</code></pre>
<p>So my question is, why it doesn't goes inside <code>if</code> when it matches to <code>M</code></p>
| <p>Because </p>
<pre><code>if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
</code></pre>
<p>Has inside <code>if (checkQueryString == "M")</code></p>
<p>So try this</p>
<pre><code>function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
} else if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
}
</code></pre>
|
Access elements inside a div outside of the current div <p>This is probably a very easy approach, however I haven't been able to figure it out.</p>
<p>My approach is to get all elements that have the "expanded-image" class that are within the "img-preview" of my current "entry".</p>
<p>This is my html:</p>
<pre><code><div class="entry">
<div class="img-preview">
<img>
<img class="expanded-image" style="display:none;">
</div>
<div class="content">
[..]
[..]
<span class="more-text"></span>
[..]
[..]
</div>
</div>
</code></pre>
<p>And this is the JS I work with:</p>
<pre><code>$('.content').each(function(event) {
$(this).find('span.more-text').click(function(event) {
// TODO
});
});
</code></pre>
| <p>Firstly you don't need the <code>each()</code> at all as you can apply the <code>click()</code> event handler to all elements within a single selector.</p>
<p>To solve your issue you can use <code>closest()</code> to find the nearest parent <code>.entry</code> element to the clicked <code>.more-text</code>. From there you can <code>find()</code> all the <code>.expanded-image</code> elements. Try this: </p>
<pre><code>$('.content span.more-text').click(function(event) {
var $imgs = $(this).closest('.entry').find('.img-preview .expanded-image');
// work with $imgs here...
});
</code></pre>
|
How to call a webservice with Parameters in Android? <p>I am new to android development. I know how to call webservice in iOS but when it comes to android I am blank. I have read many answer to it and they suggest different approaches. I have main activity and one Webservice class which extends AsynTask class. I want to call a webservice with URL "<a href="http://myURL.com/login" rel="nofollow">http://myURL.com/login</a>" with two parameters <strong>email</strong> and <strong>password</strong>. but I dont understand where I have to pass parameters and from where I can add it to URLConnection. I know it's a very basic question but I have already lost 5 hours in it. </p>
<p>my <strong>MainActivity class</strong>:</p>
<pre><code>WebService webService = new WebService(this,"http://myURL.com/login","xyz@test.com","123456");
webService.execute();
</code></pre>
<p>my <strong>WebService class</strong></p>
<pre><code> protected String doInBackground(String... params) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urlString);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
wr.close();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
</code></pre>
| <p>If you wan't use third party, you can follow this <a href="http://www.androidhive.info/2011/10/android-making-http-requests/" rel="nofollow">link</a>, hopefully can help you guys :)</p>
|
using function caller names in method chaining <p>I have the following <code>Pet</code> and <code>cat</code> inherits from <code>Pet</code>, as follows:</p>
<pre><code>function Pet(){};
Pet.prototype.run = function takeoff(cb, sec) {
setTimeout(function() {
cb();
console.log('Run');
}, sec);
};
Pet.prototype.bark = function bark(cb, sec) {
setTimeout(function() {
cb();
console.log('bark');
}, sec);
};
Pet.prototype.comeback = function comeback(cb, sec) {
setTimeout(function() {
cb();
console.log('Comeback');
}, sec);
};
var cat = new Pet();
cat.prototype = Object.create(Pet);
cat.prototype.run = function(){
var that = this;
that.run = Pet.prototype.run.call(that);
return that;
}
cat.prototype.bark = function(){
this.bark = Pet.prototype.bark.call(this);
return this;
}
cat.prototype.comeback = function(){
this.comeback = Pet.prototype.comeback.call(this);
return this;
}
console.log(cat);
cat.run().bark().return();
</code></pre>
<p>In this situation, the <code>cat</code> and <code>Pet</code> have the same function names. The only difference is <code>return this</code> is added to <code>cat</code> methods to make method chaining possible in <code>cat</code> but not <code>Pet</code>. However, note that I have to write the name of the function every time and set the same name to its parent's prototype. Is it possible to generalize this so that any method I specify for <code>Pet</code> will be duplicated in <code>cat</code> but yet I don't have to specify the method for <code>cat</code> every time? </p>
| <p>You can add a property in child classes and based on this value, you can return <code>this</code>.</p>
<h3>Sample</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Parent Class
function Pet() {
this.sec = 1000
};
Pet.prototype.run = function takeoff(cb, sec) {
setTimeout(function() {
//cb();
console.log('Run');
}, sec || this.sec);
if (this.animalName) return this;
};
Pet.prototype.bark = function bark(cb, sec) {
setTimeout(function() {
//cb();
console.log('bark');
}, sec || this.sec);
if (this.animalName) return this;
};
Pet.prototype.comeback = function comeback(cb, sec) {
setTimeout(function() {
//cb();
console.log('Comeback');
}, sec || this.sec);
if (this.animalName) return this;
};
// Child class
var Cat = function() {
this.animalName = 'Cat'
}
// Linking of classes
Cat.prototype = new Pet();
// object of child class
var cat = new Cat();
cat.run().bark().comeback()
var pet = new Pet();
try {
// Chaining not allowed.
pet.run().bark().comeback()
} catch (ex) {
console.log(ex.message)
}</code></pre>
</div>
</div>
</p>
|
android studio:Unable to create media player <blockquote>
<p>Why do i get this error? Please help!</p>
<p>10-17 09:34:13.217 17220-20262/com.example.e19adm.onlineradioplayer
E/MediaPlayer: Unable to create media player</p>
</blockquote>
<p>public class MainActivity extends AppCompatActivity {</p>
<pre><code>Button b_play;
MediaPlayer mediaPlayer;
String stream="https://www.internet-radio.com/station/danceradioukchatbox/";
boolean prepared = false;
boolean started = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play =(Button) findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("LOADING");
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (started){
started = false;
mediaPlayer.pause();
b_play.setText("PLAY");
} else {
started = true;
mediaPlayer.start();
b_play.setText("PAUSE");
}
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play.setEnabled(true);
b_play.setText("PLAY");
}
}
@Override
protected void onPause() {
super.onPause();
if (started){
mediaPlayer.pause();
}
}
@Override
protected void onResume() {
super.onResume();
if (started){
mediaPlayer.start();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (prepared){
mediaPlayer.release();
}
} }
> 0-17 10:17:35.383 32413-32413/com.example.e19adm.onlineradioplayer
> E/MediaPlayer: pause called in state 0
> 10-17 10:17:135.413 32413-19389/com.example.e19adm.onlineradioplayer I/MediaPlayer: This
> is not a sprint project
> 10-17 10:17:35.423 32413-19389/com.example.e19adm.onlineradioplayer E/MediaPlayer: Unable
> to create media player
> 10-17 10:17:35.423 32413-19389/com.example.e19adm.onlineradioplayer W/System.err:
> java.io.IOException: setDataSource failed.: status=0x80000000
> 10-17 10:17:35.423 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> android.media.MediaPlayer._setDataSource(Native Method)
> 10-17 10:17:35.423 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> android.media.MediaPlayer.setDataSource(MediaPlayer.java:1248)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> android.media.MediaPlayer.setDataSource(MediaPlayer.java:1180)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> com.example.e19adm.onlineradioplayer.MainActivity$PlayerTask$override.doInBackground(MainActivity.java:64)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> com.example.e19adm.onlineradioplayer.MainActivity$PlayerTask$override.access$dispatch(MainActivity.java)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> com.example.e19adm.onlineradioplayer.MainActivity$PlayerTask.doInBackground(MainActivity.java:0)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> com.example.e19adm.onlineradioplayer.MainActivity$PlayerTask.doInBackground(MainActivity.java:57)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> android.os.AsyncTask$2.call(AsyncTask.java:288)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> java.util.concurrent.FutureTask.run(FutureTask.java:237)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
> 10-17 10:17:35.433 32413-19389/com.example.e19adm.onlineradioplayer W/System.err: at
> java.lang.Thread.run(Thread.java:864)
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer D/[MediaPluginDLNA]:
> [getIsRegionSupported] sRegionCode: 6
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer D/[MediaPluginDLNA]:
> not in Mirror mode
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer D/MediaPlayer:
> doStart() in
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer D/MediaPlayer:
> Htc_getIntParameter get error: -38
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer E/MediaPlayer: start
> called in state 1
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer E/MediaPlayer: error
> (-38, 0)
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer D/MediaPlayer:
> Mediaplayer receives message, message type: 100
> 10-17 10:17:38.643 32413-32413/com.example.e19adm.onlineradioplayer E/MediaPlayer: Error
> (-38,0)
> 10-17 10:17:40.133 32413-32413/com.example.e19adm.onlineradioplayer E/MediaPlayer: pause
> called in state 0
</code></pre>
| <p>Consider adding the permission to access <code>INTERNET</code> to your <code>AndroidManifest.xml</code></p>
<pre><code><uses-permission android:name="android.permission.INTERNET"/>
</code></pre>
|
C# Save PictureBox Image to Remote Server <p>I have my own server with local IP is 172.23.1.66 with CentOS 7</p>
<p>So in my program, I can call image from my server with string imageLocation = "<a href="http://172.23.1.66/img/978979892782.jpg" rel="nofollow">http://172.23.1.66/img/978979892782.jpg</a>";</p>
<p>In other case, I want to save it in to my remote server. I can't access it in windows explorer, I only can access it on browser. I remote it using WinSCP.</p>
<p>I have try like this:</p>
<pre><code>picImage.Image.Save(@"\\172.23.1.66\img\" + clsLibrary.throwCode + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); // throwCode is my file name
</code></pre>
<p>but it throw <strong>An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll</strong></p>
<p>I also have try delete <strong>\\</strong> in the first of IP.</p>
<p>Everything is fail, can anyone help?</p>
| <p>Use Server MapPath to make sure you can use your URL on your server:</p>
<pre><code>picImage.Image.Save(Server.MapPath("~/img/") + clsLibrary.throwCode + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
</code></pre>
|
Assume view state with Espresso test <p>JUnit library has an <code>Assume.*</code> instructions like <code>Assume.assumeTrue(boolean)</code> which works like assertions, but not cause test to fail and just to been ignored.</p>
<p>I want to perform such checking in <code>arrange</code> part of test for one of my views, by example assume, that founded checkbox is checked before starting the <code>act</code> part of test.</p>
<p>Take a look: </p>
<pre><code>@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void deselectFilter_AllFiltersSelected_CheckboxAllSelectedUnchecked() {
//arrange
ViewInteraction checkBox = onView(
allOf(withId(R.id.cbCheckAll), isDisplayed()));
//assume that this checkbox is checked
//act
...
//assert
...
}
</code></pre>
<p>In the <code>arrange</code> part i've received not a <code>View</code>, but <code>ViewInteraction</code>.
So I can perform such <code>assertion</code> like <code>checkBox.check(matches(isChecked()))</code><br/>
But how to perform assume?</p>
| <p>The only way i've founded at this moment is just finding assuming view manually with activity from test rule. And then assume via jUnit. </p>
<pre><code>CheckBox checkBox = (CheckBox) mActivityTestRule.getActivity().findViewById(R.id.cbCheckAll);
Assume.assumeTrue(checkBox.isChecked());
</code></pre>
<p>If you know a better way, maybe with using Espresso, please answer. Seems that it impossible to access view directly from Espresso commands</p>
|
Using protected $relations in User model? <p>I have two tables: <code>Users, Workers</code>.</p>
<p>The relationship is: <code>Users.id = Workers.user_id</code></p>
<p>In <code>User model</code> I set related model as:</p>
<pre><code>protected $relations = ['workers'];
</code></pre>
<p>And there is method <code>workers</code> in User model:</p>
<pre><code>public function workers()
{
return $this->hasOne('App\Workers', "user_id");
}
</code></pre>
<p>So, in conclusion when I catch the object:</p>
<pre><code>dd(Auth::user());
</code></pre>
<p>I dont have here attributes from related model <code>workers</code></p>
| <p>You should use <code>workers()</code> relation to get this info:</p>
<pre><code>dd(Auth::user()->workers());
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.