input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Pizza Parallel Arrays <p>I need to define three arrays (Size, Price, and Extra). I then had to ask them their size and their choice for toppings. </p>
<p>Using a for loop and the parallel array technique, walk through the size array to find the size that matches the userâs input. Using the current index of your loop, look up the price for that size in the price array, and write out to the user how much the pizza will cost. </p>
<p>If the user said they do want extra toppings, still using the same index for your loop, look up how much that costs in your extra array, and tell the user the total cost for the pizza.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] sizes = { "S", "M", "L", "X" };
double[] prices = { 6.99, 8.99, 12.50, 15.00 };
double[] extra = { 1.00, 2.00, 3.25, 4.50 };
string inputToppings;
string inputSize;
Console.Write("What size pizza would you like? Enter S, M, L, or X: ");
inputSize = Console.ReadLine();
Console.Write("Would you like extra toppings? Enter Y or N: ");
inputToppings = Console.ReadLine();
for (int i = 0; i < sizes.Length; i++)
{
if (sizes[i] == inputSize)
{
Console.WriteLine("You ordered a {0} pizza that costs {1:C}.", sizes[i], prices[i]);
break;
}
}
Console.ReadLine();
}
}
}
</code></pre>
<p>My Problem is that I can get the correct input for the Pizza Size and Prices, but I cannot a working statement to display the price of the pizza size WITH the toppings in the form of a WriteLine. I have spent hours on this and I cannot find a working method. Please help...</p>
| <p>Try changing your "for" loop to:</p>
<pre><code> for (int i = 0; i < sizes.Length; i++)
{
if (sizes[i] == inputSize)
{
var totalPrice = prices[i] + (inputToppings == "Y" ? extra[i] : 0);
Console.WriteLine("You ordered a {0} pizza that costs {1:C}.", sizes[i], totalPrice);
break;
}
}
</code></pre>
<p>'Hope this helps.</p>
|
Primitive / Non-Nullable typenames in C# <p>What are the primitive typenames in C#? Yes, we have a similar answer, but that only mention types, not the typenames:
<a href="http://stackoverflow.com/a/13530321/3691653">http://stackoverflow.com/a/13530321/3691653</a></p>
<p>E.g. it mentions types such as <code>System.Int32</code> and <code>System.Single</code> but not typenames <code>int</code> and <code>float</code> which also compiles for me. So what is the full list of typenames including its aliases?</p>
<p>In other words, I am interested about non-nullable typenames / typenames that require the Nullable<> keyword in order to be able to be set as null.</p>
| <p>Like these:</p>
<pre><code>alias type (in System namespace)
byte Byte
sbyte SByte
short Int16
ushort UInt16
int Int32
uint UInt32
long Int64
ulong UInt64
decimal Decimal
float Single
double Double
</code></pre>
<p>Read the rest at <a href="https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx</a></p>
|
Margins Prevent Text Align; <p>(If there is a simpler solution to this problem, please tell me)</p>
<p>I want this website to have 2 sections of text, one on each side of the screen.</p>
<p>I did this successfully. I used text align and translate3d to move the text to the right, then up.</p>
<p>The only problem was that the width of the the text on the right blocked the text on the left from being interacted with. </p>
<p>I decided to change the width of the text on the right side, and when I did, the text alignment wasn't working, because of the margins (the inspect said margins).</p>
<p>I decided to change the margins to 0, and nothing happened.</p>
<p>I have no idea why, but here is some code:</p>
<pre><code>.mid{
margin: 0px 0px 0px 0px;
font-family:myfont;
font-size:150px;
}
.midl{
text-align:left;
}
.midr{
width:625px;
text-align:right;
transform:translate3d(0,-181px,0)
}
</code></pre>
<hr>
<pre><code></div>
<div id="midwlink">
<p id="games" class="mid midl">Games</p>
<p id="calculators" class="mid midr">Calculators</p>
<p id="animations" class="mid midl">Animations</p>
<p id="pictures" class="mid midr">Pictures</p>
</div>
</code></pre>
<hr>
<p>I later added this, but still nothing happened:</p>
<pre><code>#calculator{
margin: 0 !important;
}
</code></pre>
<hr>
<p>So, is there any possible way to have text on both sides of the screen at the same time, with them being separate from each other?</p>
<p>Or is there a way to COMPLETELY remove margins?</p>
| <p>There are many ways to achive side by side layouts in HTML. One of the simplest is to use two divs side by side, as in this snippet.</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>div {
width: 49%;
display: inline-block;
}
div.right {
text-align: right
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left">
Hello left
</div>
<div class="right">
Hello right
</div></code></pre>
</div>
</div>
</p>
|
Application of functions and Kleisli arrows <p><code>(.)</code> and <code>(<=<)</code> are quite similar:</p>
<pre><code>(.) :: (b -> c) -> (a -> b) -> (a -> c)
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
</code></pre>
<p>and are available as a method in the <code>Category</code> type class (<code>(->)</code> and <code>Kleisli</code> instances):</p>
<pre><code>(<<<) :: (Category f) => f b c -> f a b -> f a c
</code></pre>
<p><code>($)</code> and <code>(=<<)</code> are also quite similar:</p>
<pre><code>($) :: (a -> b) -> a -> b
(=<<) :: Monad m => (a -> m b) -> m a -> m b
</code></pre>
<p>Is there a type class that abstracts over these application functions?</p>
| <p>As Daniel's comment says, <code>(=<<)</code> already encompasses <code>($)</code>. There is already a newtype (similar to how there is a <code>Kleisli</code> newtype for <code>a -> m b</code> for <code>Category</code>) for <code>a</code> called <a href="http://hackage.haskell.org/package/base-4.9.0.0/docs/Data-Functor-Identity.html" rel="nofollow"><code>Identity</code></a>, which has a <code>Monad</code> instance such that</p>
<pre><code>f $ x
</code></pre>
<p>corresponds to </p>
<pre><code>Identity . f =<< Identity x
</code></pre>
<hr>
<p>While there are subcomponents that are reused in <code>(.)</code> and <code>(<=<)</code> (namely <code>a -> b</code> in the former and <code>a -> m b</code> in the latter) which can be abstracted out to a typeclass for a type constructor <code>a :: * -> * -> *</code> (which turns out to be <code>Category</code>), the largest such subcomponent in <code>($)</code> and <code>(=<<)</code> is just <code>a</code> in the former and <code>m a</code> in the latter.</p>
|
JQuery calendar not working after ajax call, but the button is there? <p>i'm having an issue here with JQuery calendar, it doesn't work after an ajax call. I've tried a lot of options, but any of them worked</p>
<p>this is my js:</p>
<pre><code>function carregar(metodo, div) {
var loading = new Image();
loading.src = "${resource(dir: 'images', file: spinner.gif)}";
$.ajax({
url: metodo,
type: "GET",
dataType: 'text',
beforeSend: function () {
$("#" + div).html(loading);
},
success: function (data) {
$("#" + div).html(data);
}
});
}
$(function () {
$("#nascimento").datepicker({
showOn: "button",
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: true
});
});
</code></pre>
<p>this is the index, where I call the ajax function:</p>
<pre><code><%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta name="layout" content="main" />
<title>Cadastrar Aluno</title>
</head>
<body>
<input type="button" value="Novo" onClick="carregar('/aluno/novo', 'divForm')"/>
<input type="button" value="Pesquisar" onClick="carregar('/aluno/pesquisar', 'divForm')"/>
<div id="divForm">
<g:render template="form"></g:render>
</div>
</body>
</html>
</code></pre>
<p>And this is my form template:</p>
<pre><code><asset:javascript src="application.js"/>
<g:uploadForm controller="aluno" action="salvar">
//other fields
<label>Data de Nascimento:</label>
<input type="text" name="nascimento" id="nascimento" required="true" value="<g:formatDate format="dd-MM-yyyy" date="${aluno?.nascimento}"/>"/><br>
//other fields
<input type="submit" value="Salvar"/>
<input type="button" name="btnCancelar" value="Cancelar"/>
<input type="hidden" name="id" value="${aluno?.id}">
</g:uploadForm>
</code></pre>
<p>If I put </p>
<pre><code><script type="text/javascript">
$(function() {
$( "#nascimento" ).datepicker();
});
</script>
</code></pre>
<p>in the template, ir works one time, If I load the "form" template again after reloading the page, it doesn't.</p>
<p>I've tried this:
<a href="http://stackoverflow.com/questions/27577558/jquery-datepicker-doesnt-work-after-ajax-call-if-its-already-on-page">jquery datepicker doesn't work after ajax call if its already on page</a>
<a href="http://stackoverflow.com/questions/20453879/jquery-datepicker-not-working-after-ajax-call">JQuery datepicker not working after ajax call</a>
<a href="http://stackoverflow.com/questions/14087501/jquery-datepicker-does-not-work-after-ajax-call">jQuery datepicker does not work after Ajax call</a></p>
<p>do you guys have any ideas? </p>
<p>thanks!</p>
| <p>When you reload your html, you are destroying the element that had the datepicker attached to it and recreating it anew.</p>
<p>As such, you'll need to re-initialize the datepicker after you replace the html, with something like this:</p>
<pre><code> success: function (data) {
$("#" + div).html(data);
$("#nascimento").datepicker('remove').datepicker({
showOn: "button",
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: true
});
}
</code></pre>
|
How to pass specific value to one thread? <p>I'm working through a thread exercise in C, it's a typical thread scheduling code many schools teach, a basic one can be seen here, my code is basically the same except for my altered runner method
<a href="http://webhome.csc.uvic.ca/~wkui/Courses/CSC360/pthreadScheduling.c" rel="nofollow">http://webhome.csc.uvic.ca/~wkui/Courses/CSC360/pthreadScheduling.c</a></p>
<p>What I'm doing is basically altering the runner part so my code prints an array with random numbers within a certain range, instead of just printing some words. my runner code is here:</p>
<pre><code>void *runner(void *param) {
int i, j, total;
int threadarray[100];
for (i = 0; i < 100; i++)
threadarray[i] = rand() % ((199 + modifier*100) + 1 - (100 + modifier*100)) + (100 + modifier*100);
/* prints array and add to total */
for (j = 0; j < 100; j += 10) {
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n", threadarray[j], threadarray[j+1], threadarray[j+2], threadarray[j+3], threadarray[j+4], threadarray[j+5], threadarray[j+6], threadarray[j+7], threadarray[j+8], threadarray[j+9]);
total = total + threadarray[j] + threadarray[j+1] + threadarray[j+2] + threadarray[j+3] + threadarray[j+4] + threadarray[j+5] + threadarray[j+6] + threadarray[j+7] + threadarray[j+8] + threadarray[j+9];
}
printf("Thread %d finished running, total is: %d\n", pthread_self(), total);
pthread_exit(0);
}
</code></pre>
<p>My question lies in the first for loop where I'm assigning random numbers to my array, I want this modifier to change based on which thread it is, but I can't figure out how to do it, for example if its the first thread the range will be 100-199, 2nd will be 200-299, etc and so on. I have tried to assign i to an value before doing pthread_create and assigning that value to an int in runner to use as the modifier, but since there are 5 concurrent threads it ends up assigning this number to all 5 threads, and they end up having the same modifier. </p>
<p>So I'm looking for a method to approach this where it will work for all the individual threads instead of assigning it to all of them, I have tried to change the parameters to something like <code>(void *param, int modifier)</code> but when I do this I have no idea how to reference runner, since by default it's refrenced like <code>pthread_create(&tid[i],&attr,runner,NULL);</code></p>
| <p>You want to make <code>param</code> point to a data structure or variable who's lifetime will exist longer than the thread lifetime. And you cast the <code>void*</code> parameter to the actual data type it was allocated as.</p>
<p>Easy example:</p>
<pre><code>struct thread_data
{
int thread_index;
int start;
int end;
}
struct thread_info;
{
struct thread_data data;
pthread_t thread;
}
struct thread_info threads[10];
for (int x = 0; x < 10; x++)
{
struct thread_data* pData = (struct thread_data*)malloc(sizeof(struct thread_data)); // never pass a stack variable as a thread parameter. Always allocate it from the heap.
pData->thread_index = x;
pData->start = 100 * x + 1;
pData->end = 100*(x+1) - 1;
pthread_create(&(threads[x].thread), NULL, runner, pData);
}
</code></pre>
<p>Then your runner:</p>
<pre><code>void *runner(void *param)
{
struct thread_data* data = (struct thread_data*)param;
int modifier = data->thread_index;
int i, j, total;
int threadarray[100];
for (i = 0; i < 100; i++)
{
threadarray[i] = ...
}
</code></pre>
|
Iterating an Array List to calculate the percentage of population growth <p>I want to create a method calculate the percent change of population growth from the years 1994-2013, and prints out each percentage change. I have the data all stored in, but I am not sure how to iterate the ArrayList to accomplish this</p>
<pre><code>import java.io.*;
import java.util.*;
public class USCrimeClass
{
public int year;
public int population;
public int violentCrime;
public double violentCrimeRate;
public int manslaughter;
public double manslaughterRate;
public int rape;
public double rapeRate;
public int robbery;
public double robberyRate;
public int assault;
public double assaultRate;
public int propertyCrime;
public double propertyCrimeRate;
public int burglary;
public double burglaryRate;
public int larcenyTheft;
public double larcenyTheftRate;
public int vehicleTheft;
public double vehicleTheftRate;
public USCrimeClass(String line)
{
String[]split=line.split(",");
year=Integer.parseInt(split[0]);
population=Integer.parseInt(split[1]);
violentCrime=Integer.parseInt(split[2]);
violentCrimeRate=Double.parseDouble(split[3]);
manslaughter=Integer.parseInt(split[4]);
manslaughterRate=Double.parseDouble(split[5]);
rape=Integer.parseInt(split[6]);
rapeRate=Double.parseDouble(split[7]);
robbery=Integer.parseInt(split[8]);
robberyRate=Double.parseDouble(split[9]);
assault=Integer.parseInt(split[10]);
assaultRate=Double.parseDouble(split[11]);
propertyCrime=Integer.parseInt(split[12]);
propertyCrimeRate=Double.parseDouble(split[13]);
burglary=Integer.parseInt(split[14]);
burglaryRate=Double.parseDouble(split[15]);
larcenyTheft=Integer.parseInt(split[16]);
larcenyTheftRate=Double.parseDouble(split[17]);
vehicleTheft=Integer.parseInt(split[18]);
vehicleTheftRate=Double.parseDouble(split[19]);
}
Scanner read = null;
{
try
{
read=new Scanner(new File("C:\\Crime.csv"));
}
catch(FileNotFoundException e)
{
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeClass> crimeClasses = new ArrayList<>();
read.nextLine();
while(read.hasNextLine())
{
crimeClasses.add(new USCrimeClass(read.nextLine()));
}
read.close();
}
}
</code></pre>
| <p>Some of the items I'm going to point out are more code review items that aren't specifically related to the business logic of what you're trying to do, however, in the long run your code will be more readable and maintainable.</p>
<p>First, it's a good idea to separate your data model from your controller logic. The controller handles the business logic whereas the data model stores the data and provides methods to access and change the data. You should also name the class appropriately - using the name <code>USCrimeClass</code> could be improved because it's obvious that this is a class, you don't have to use the word "class" in the name. You should also create getter and setter methods for your class member variables rather than allowing direct access. In the code sample below I have created a single getter and setter pair for the <code>population</code> field as an example.</p>
<pre><code>public class USCrimeData {
private int year;
private int population;
private int violentCrime;
private double violentCrimeRate;
private int manslaughter;
private double manslaughterRate;
private int rape;
private double rapeRate;
private int robbery;
private double robberyRate;
private int assault;
private double assaultRate;
private int propertyCrime;
private double propertyCrimeRate;
private int burglary;
private double burglaryRate;
private int larcenyTheft;
private double larcenyTheftRate;
private int vehicleTheft;
private double vehicleTheftRate;
public USCrimeData(String line) {
String[] split = line.split(",");
year = Integer.parseInt(split[0]);
population = Integer.parseInt(split[1]);
violentCrime = Integer.parseInt(split[2]);
violentCrimeRate = Double.parseDouble(split[3]);
manslaughter = Integer.parseInt(split[4]);
manslaughterRate = Double.parseDouble(split[5]);
rape = Integer.parseInt(split[6]);
rapeRate = Double.parseDouble(split[7]);
robbery = Integer.parseInt(split[8]);
robberyRate = Double.parseDouble(split[9]);
assault = Integer.parseInt(split[10]);
assaultRate = Double.parseDouble(split[11]);
propertyCrime = Integer.parseInt(split[12]);
propertyCrimeRate = Double.parseDouble(split[13]);
burglary = Integer.parseInt(split[14]);
burglaryRate = Double.parseDouble(split[15]);
larcenyTheft = Integer.parseInt(split[16]);
larcenyTheftRate = Double.parseDouble(split[17]);
vehicleTheft = Integer.parseInt(split[18]);
vehicleTheftRate = Double.parseDouble(split[19]);
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
</code></pre>
<p>Next let's talk about the controller. This is where the business logic will reside. This is where you will use your data model to arrive at the results you desire. Since you want to determine the percent population change you would use the list of crime data to get the population from the year 1994 (I assume this is the first entry in the list - index 0) and then get the last entry in the list (I assume the final entry is 2013) then calculate the value you want. If these assumptions are not correct or if you want to calculate growth for different years you would want to implement a <code>getYear()</code> method in your data model and then loop through your list of data until you find the object with the year you want.</p>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Controller {
public static void main(String[] args) {
Scanner read = null;
try {
// Replace the "..." below with actual path to your data file.
read = new Scanner(new File("..."));
} catch (FileNotFoundException e) {
System.out.println("The file can't be opened");
System.exit(0);
}
List<USCrimeData> crimeClasses = new ArrayList<>();
while (read.hasNextLine()) {
crimeClasses.add(new USCrimeData(read.nextLine()));
}
read.close();
int initialPopulation = crimeClasses.get(0).getPopulation();
System.out.println("initialPopulation: "+initialPopulation);
int latestPopulation = crimeClasses.get(crimeClasses.size()-1).getPopulation();
System.out.println("latestPopulation: "+latestPopulation);
double percentGrowth = (double)(latestPopulation - initialPopulation) / initialPopulation * 100;
System.out.println("percentGrowth: "+percentGrowth);
}
}
</code></pre>
|
I'm trying to write a line of code at ask the user for two inputs but can't figure out how to complete this <h1>Why does this line of code not split the two</h1>
<pre><code>Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split()
</code></pre>
| <p>By default using <code>split()</code> will only split on a space. You are asking the user to enter two entries separated by a <code>,</code>, so you will end up getting a</p>
<pre><code>ValueError: not enough values to unpack (expected 2, got 1)
</code></pre>
<p>To resolve this, you need to split on the identifier you are looking to split with. In this case it is a ',', so call <code>split</code> as <code>split(',')</code>:</p>
<pre><code>Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split(',')
</code></pre>
<p>Demo:</p>
<pre><code>>>> Lat1,long1 = input("Enter the Lat and Long of the source point separated by a comma eg 20,30").split(',')
Enter the Lat and Long of the source point separated by a comma eg 20,3060,80
>>> Lat1
'60'
>>> long1
'80'
</code></pre>
<p>Here is the documentation on split:</p>
<p><a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow">https://docs.python.org/3/library/stdtypes.html#str.split</a></p>
|
Why does this code take so long to be executed? - Python <p>I coded this on Python. It took way too long to finish if the input were just 40x40 (it's for image processing using <code>numpy</code>). Its behavious is the following: there's an array with objects in it (which have an 'image' attribute which is a numpy array) and then I check if that object is somewhere in another array, and then take the next from the first array and repeat the process until I've checked if all are in the other array:</p>
<pre><code> #__sub_images is the array containing the objects to be compared
#to_compare_image is the image that is received as parameter to check if the objects are in there.
#get_sub_images() is just to retrieve the objects from the array from the received array to find.
#get_image() is the method that retrieves the attribute from the objects
same = True
rows_pixels = 40 #problem size
cols_pixels = 40 #problem size
i = 0 #row index to move the array containing the object that must be checked if exist
j = 0 #col index to move the array containing the object that must be checked if exist
k = 0 #row index to move the array where will be checked if the object exist
l = 0 #col index to move the array where will be checked if the object exist
while i < len(self.__sub_images) and k < len(to_compare_image.get_sub_images()) and l < len(to_compare_image.get_sub_images()[0]):
if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()):
same = False
else:
same = True
k = 0
l = 0
if j == len(self.__sub_images[0]) - 1:
j = 0
i += 1
else:
j += 1
if not same:
if l == len(to_compare_image.get_sub_images()[0]) - 1:
l = 0
k += 1
else:
l += 1
</code></pre>
<p>I managed to code it with just a <code>while</code>, instead of 4 <code>for-loops</code> which is what I used to do before. Why is it taking so long still? Is it normal or is there something wrong? The complexity is supposed to be x and not xâ´</p>
<p>The code that is not included are just getters, I hope you can understand it with the <code>#notes</code> at the begining.</p>
<p>THanks.</p>
| <p>Instead of this:</p>
<pre><code>if not np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image()):
same = False
else:
same = True
#snip
if not same:
#snip
</code></pre>
<p>You can do this:</p>
<pre><code>same=np.array_equal(self.__sub_images[i][j].get_image(), to_compare_image.get_sub_images()[k][l].get_image())
if same:
#snip
else:
#snip
</code></pre>
<p>This uses less if-branches than before.</p>
|
what is the equivalent of an if-statement in ARM? <p>So, I am working on a program in ARM that takes a bunch of numbers from a file and tells if they are even or odd. </p>
<p>The problem is that I know how to multiply by 0.5, but I don't know how to do something like this high level statement in ARM</p>
<pre><code>if (A / 2 == 0)
print even
else
print odd
</code></pre>
<p>Here's what I have in terms of code:</p>
<pre><code>@open input file
ldr r0,=FileName @ set Name for input file
mov r1,#0 @ mode is input
swi SWI_Open @ open file for input
bcs InFileError @ if error?
ldr r1,=InFileHandle @ load input file handle
str r0,[r1] @ save the file handle
@read integers from input file
NUMBERS:
ldr r0,=InputFileHandle @ load input file handle
ldr r0,[r0]
swi SWI_RdInt @ read the integer into R0
bcs EofReached @ Check Carry-Bit (C): if= 1 then EOF reached
@multiplication by 0.5 to test for odd or even
MUL R2 R0 0.5
@what is the test in ARM
@for ( R0 / 0.5 ) == a multiple of 1?
B NUMBERS
LOOP:
@end of program
Message1: .asciz"Hello World!"
EOL: .asciz "\n"
NewL: .ascii "\n"
Blank: .ascii " "
FileName: .asciz"input.txt"
.end
</code></pre>
<p>So I think the first two things inputting from the file and reading the integers works. I don't know how to test for the condition that it is divisible by 2. I think it's multiplied by 0.5 and then the next step is to say even if that number doesn't have a decimal place with anything after it at the end, but if it does then then number A that was divided into number B is odd. Otherwise it is even?</p>
| <p>A brief answer: you don't need to multiply by 0.5 or anything like that. You need to check the value of LSB (least significant bit) of the value. It will be 0 for even numbers and 1 for odd numbers.</p>
<p>Upd.: your "C" code is also wrong. You want to use A % 2, not A / 2</p>
|
Accessing elements in a multidimensional array in PHP <p>I am trying to associate every subdomain, from a list, with its main domain name and I am doing this like so:</p>
<pre><code><?php
$main_domains = ['example.co.uk','example.com','example.org'];
$subdomains = ['sub.example.com','ftp.example.org','ftp.example.co.uk','mail.example.com'];
$results = [];
foreach ($subdomains as $subdomain) {
foreach ($main_domains as $domain) {
if (strpos($subdomain, $domain) !== false) {
$results[$domain][] = $subdomain;
continue;
}
}
}
</code></pre>
<p>Where in the end <code>$results</code> contains the following:</p>
<pre><code>array(3) {
["example.com"]=>
array(2) {
[0]=>
string(15) "sub.example.com"
[1]=>
string(16) "mail.example.com"
}
["example.org"]=>
array(1) {
[0]=>
string(15) "ftp.example.org"
}
["example.co.uk"]=>
array(1) {
[0]=>
string(17) "ftp.example.co.uk"
}
}
</code></pre>
<p>However, I would now like to echo out the information like so:</p>
<pre><code><main domain> <sub domain>
<main domain> <sub domain>
...
</code></pre>
<p>i.e:</p>
<pre><code>example.com sub.example.com
example.com mail.example.com
example.org ftp.example.org
example.co.uk ftp.example.co.uk
</code></pre>
<p>How can I do that?</p>
| <p>most importantly is to set up the initial structure.</p>
<pre><code>$dom=array('example.co.uk'=>array('ftp.example.co.uk','zzz.example.co.uk'));
foreach($dom as $domain=>$sub){
foreach($sub as $s){
echo $domain.' '.$s."\n";
}
}
</code></pre>
<p>output:</p>
<blockquote>
<p>example.co.uk ftp.example.co.uk<br> example.co.uk zzz.example.co.uk</p>
</blockquote>
<p>exacly what you asked for.</p>
|
Java 8 lambda expression bytecode consistency <p>I've been digging through Java lambda expression bytecode as compiled by my OpenJDK compiler, and I'm wondering, can lambda expression bytecode vary by compiler/runtime? I'd like to know that my inspection logic will work across platforms, or not.</p>
| <blockquote>
<p>can lambda expression bytecode vary by compiler/runtime?</p>
</blockquote>
<p>In theory yes. The JLS does NOT specify that particular bytecodes / sequences must be generated. </p>
<p>You would need to check the bytecodes emitted by existing Java 8 & Java 9 compilers to see how much they differ. (And that doesn't tell you about compilers / versions that are yet to be written!)</p>
<blockquote>
<p>I'd like to know that my inspection logic will work across platforms, or not.</p>
</blockquote>
<p>The solution should be to build a comprehensive set of test cases and run them against the code produced by all Java compilers that you want to support.</p>
<p>In short: test it.</p>
|
If statemtent is true dont run else <p>I have two buttons one in <code>if(button1)</code> and the other in <code>else(button2)</code></p>
<p>How can i make it so that if the <code>if(button1)</code> is executed it doesn't let the user do use <code>else(button2)</code>?</p>
<p>The bug i have is when i press <strong>Button1</strong> it runs its, code but when i press <strong>Button2</strong> before <strong>Button1</strong> is finished its run, both start running at the same time.</p>
| <p>The <strong>else statement</strong> is to be executed if the <strong>if statement</strong> is false. So by default, if the <strong>if statement</strong> is true and ends up executing, the <strong>else statement</strong> will not run.</p>
|
How to bypass or ignore a number? <p>Hey guys python noobie here. I'm trying to determine which type of credit card a user has and whether it's valid or not. For the following example, Visa cards start with the number 4 and both cards would be valid because they both start with 4. If there are zeros in front, you would skip them. Is there a built in function to bypass a number or do I have to type in every case scenario? Thank you for your time. </p>
<p>Example: </p>
<pre><code>#VISA 0004222222222222 valid
#VISA 4111111111111111 valid
</code></pre>
<h1>Luhns Algorithm</h1>
<p>def calculation( creditNumber ):
length = len( creditNumber )
oddSum = 0
evenSum = 0</p>
<pre><code>if ( length == 0 ):
return 0
else:
if length % 2 == 0:
last_number = int( creditNumber[-1])
evenSum = evenSum + last_number
return evenSum + calculation( creditNumber[:-1] )
else:
last_number = int( creditNumber[-1] )
last_number = 2 * last_number
addSum = last_number // 10 + last_number % 10
oddSum = oddSum + addSum
return oddSum + calculation( creditNumber[:-1] )
def luhnsCheck():
creditNumber = input ( "What is your credit card number?" )
#Check to see which type of credit card the user has
# American Express starts with 34 or 37
if creditNumber[0-15]
# Discover starts with 6011
# MasterCard starts with 51 or 52 or 53 or 54 or 55
# VISA starts with 4
creditcard_number = calculation( creditNumber )
# Valid Card
if creditcard_number % 10 == 0:
print( "Valid card" )
# Invalid Card
else:
print( "We do not accept that kind of card" )
</code></pre>
<p>luhnsCheck()</p>
| <p>You could copy then number and put that number in a list. Then if the first number is zero then remove it from the list. Repeat this until there is no zero in front. </p>
|
Rails: Capistrano change database.yml to database.yml.example causes error <p>When I deploy a new app to nginx using Capistrano. <br>
I follow tutorial to do <code>git mv database.yml database.yml.example</code> and <code>git mv secrets.yml secrets.yml.example</code> , then created a new <code>database.yml</code> file on remote server. But now when I want to run app on my local mechine, it shows me an error </p>
<blockquote>
<p>No such file - ["config/database.yml"]</p>
</blockquote>
<p>Because there is no database.yml on my local repo.<br>
Can I create an new and empty <code>database.yml</code> to fix this?</p>
| <p>The guide just tells you that storing database credentials in a repository is bad practice and you shouldn't do it, but it doesn't mean you don't need to have this files at all.You application still needs it, so you definitely need to create it, just don't store it in main repo with code, this security critical information is better to store it elsewhere you decide to keep your authentification data like separate repository for credentials, key-pass storage or whatever place you want for such critical information.</p>
<p><strong>PS</strong> Of course, if you just learning since it's not a big deal, you COULD keep your "root-123" credits in repository, but it's better to develop right habit from the beginning or at least get the idea why it should be separated.</p>
|
delete rows and return an id of the deleted rows <p>is it possible to delete a row and return a value of the deleted row?</p>
<p>example
<code>DELETE FROM table where time <= -1 week
SELECT all id that were deleted</code></p>
| <p>If you want to control the operations in the database, you could consider to use JOURNAL tables. There's a question <a href="http://stackoverflow.com/questions/9484714/how-to-store-datas-change-history">here</a> in SO about this.</p>
<p>They are a mirrored table, usually populated by a trigger with the operation performed (update, delete). It stores the "old values" (the current values you can always get from the main table).</p>
<p>If implemented so, you could then SELECT from the journal table and have exactly what you needed.</p>
<p>Trying to give you an example:</p>
<p>Table USER</p>
<pre><code>CREATE TABLE USER (
INT id,
VARCHAR name
)
</code></pre>
<p>Table USER_JN</p>
<pre><code>CREATE TABLE USER_JN (
INT id,
VARCHAR name,
VARCHAR operation
)
</code></pre>
<p>Then, for every operation you can populate the USER_JN and have a history of all changes (you should not have constraints in it).</p>
<p>If you delete, your <code>operation</code> column would have the <code>delete</code> value and you could use your select to check that.</p>
<p>It's not exactly "selecting the deleted row", but a way to make it possible.</p>
<p>Hope it's somehow useful.</p>
|
Set size of inner arrays in Java <p>I have an ArrayList of Arrays:</p>
<pre><code>ArrayList<byte[]> arrayOfBytes = new ArrayList <>();
</code></pre>
<p>I want (and I don't know how) to set a predefined size of the Inner Arrays (the bytes arrays).</p>
<p>Is this possible? If it is, how can I do it?</p>
<p>Thanks in advance!</p>
| <p>The one and only way is to set the size when you're adding those arrays into the list.</p>
<pre><code>list.add(new byte[size]);
</code></pre>
<p>There are no arrays in the List without you explicitly adding them. Just create the arrays at the right size.</p>
|
awk/sed: Insert file content before last line of specific block number <p>Given are two files, the first is an Apache config file:</p>
<pre><code>$ cat vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 3
foobar 1
barfoo 1
foobar 2
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 4
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
</code></pre>
<p>And the second file contains lines that should be added to the end of one (variable) specific VirtualHost block:</p>
<pre><code>$ cat inserted.txt
inserted line 1
inserted line 2
</code></pre>
<p>The result should look like this:</p>
<pre><code>$ cat vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
inserted line 1
inserted line 2
</VirtualHost>
<VirtualHost *:443>
vhost 3
foobar 1
barfoo 1
foobar 2
barfoo 2
</VirtualHost>
<VirtualHost *:443>
vhost 4
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
</code></pre>
<p>I tried it with some variations of the following sed but that didn't do the trick:</p>
<pre><code>$ sed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
</code></pre>
<p>I can't figure out how to select only the one VirtualHost block i need to insert the file to and since i've to use FreeBSD sed (or awk) i also get this error with previous sed command:</p>
<pre><code>$ sed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
sed: 2: "}
": unused label 'a;n;/^<\/VirtualHost/!ba;r inserted.txt'
</code></pre>
<p>With GNU sed i get the this output:</p>
<pre><code>$ gsed -e '/^<VirtualHost/{:a;n;/^<\/VirtualHost/\!ba;r inserted.txt' -e '}' vhosts-ssl.conf
<VirtualHost *:443>
vhost 1
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 2
foobar 2
barfoo 1
foobar 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 3
foobar 1
barfoo 1
foobar 2
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
<VirtualHost *:443>
vhost 4
foobar 1
foobar 2
barfoo 1
barfoo 2
</VirtualHost>
inserted line 1
inserted line 2
</code></pre>
<p>As i would like to understand my mistakes and lern from them, i would prefer answers with some explanation and maybe even some links to rtfm, thanks.</p>
<p>Added 2016-10-16</p>
<p>Pseudocode:</p>
<pre><code>if BLOCK begins with /^<VirtualHost/
and ends with /^<\/VirtualHost/
and is the ${n-th} BLOCK
in FILE_1
then insert content of FILE_2
before last line of ${n-th} BLOCK
without touching rest of FILE_1
endif
save modified FILE_1
</code></pre>
<p>The ${n-th} is gathered by:</p>
<pre><code>$ httpd -t -D DUMP_VHOSTS | \
grep -i "${SUBDOMAIN}.${DOMAIN}" | \
awk '/^[^\ ]*:443[\ ]*/ {print $3}' | \
sed -e 's|(\(.*\))|\1|' | \
cut -d: -f2
</code></pre>
<p>Output is a the number of the BLOCK i want to extend by FILE_2</p>
<p>And please only non-GNU versions as i'm on FreeBSD, thanks.</p>
| <p><code>awk</code> to the rescue!</p>
<p>requires multi-char record separator, supported by <code>gawk</code></p>
<pre><code>$ awk 'NR==FNR{insert=$0; next}
{print $0 (FNR==2?insert:"") RT}' RS='^$' insert.file RS="</VirtualHost>" file
</code></pre>
<p>read the first file in complete and assign to the variable insert, while iterating the second file at the end of second record print the variable after the record contents.</p>
<p>Another version for plain <code>awk</code></p>
<pre><code>$ awk 'NR==FNR{insert=insert?insert ORS $0:$0; next}
/<\/VirtualHost>/ && ++c==2{print insert} 1' insert.file file
</code></pre>
|
How to print full array inside a block or outside block? <p>Hello I have an array of floats, but I just can't print the full array </p>
<p>here's the first block which saves successfully the floats into the array floatDataArray</p>
<pre><code> double valuesArray[882000];
double *floatDataArray = valuesArray;
__block int j = 0;
//sampleInfo.size = 0;
[AEAudioFileReader readFileAtURL:amen.url targetAudioDescription:desc readBlock: ^(const AudioBufferList *buffer,UInt32(mBufferBlock)){
AudioBuffer audioBuffer = buffer->mBuffers[0];
float *samplesAsCArray = (float *)audioBuffer.mData;
printf("\n%i", buffer->mBuffers[1]);
for (int i = 0; i<mBufferBlock; i++) {
floatDataArray[j] = (double)samplesAsCArray[i] ; //PUT YOUR DATA INTO FLOAT ARRAY
// printf("\n%f",floatDataArray[j]); //PRINT YOUR ARRAY'S DATA IN FLOAT FORM RANGING -1 TO +1
i++;
j++;
}
</code></pre>
<p>Then the completion block where it goes thru all the buffers first</p>
<pre><code> } completionBlock:^(NSError* error){
printf("\n%@",floatDataArray); //Print full array
}];
</code></pre>
<p>which I'm able to print single values such as floatDataArray[0] but not the full one it sends nothing using %@, %s</p>
| <p>If you want to print a C array of floats you will need to write a function to do so. You can't use <code>printf</code> or <code>NSLog</code> to print a C array without writing a for loop</p>
<p>If you were to uncomment the <code>printf</code> line in your top block of code you'd see your array. However, if you really have 882,000 entries in the array printing them all to the console will take a LOOOOOOOOOOOOONG time, and not be very useful.</p>
<pre><code>for (int i = 0; i<mBufferBlock; i++) {
printf("\n%f", floatDataArray[i]
}
</code></pre>
<p>You might want to limit the output to a fixed number of digits to make the output file smaller. If you use 6 digits of precision:</p>
<pre><code>for (int i = 0; i<mBufferBlock; i++) {
printf("\n%06f", floatDataArray[i]
}
</code></pre>
<p>Then you'll have 9 bytes of output for values <10, plus another byte/value for each extra integer digit in your value (1000.000001 would take 12 bytes, including the carriage return at the end.) If all the output takes 12 bytes, that means your output log file would be about 10.5 mb. That's a <strong>LOT</strong> of text.</p>
|
UWP Background Media Playback <p>I'm trying to follow <a href="https://msdn.microsoft.com/pl-pl/windows/uwp/audio-video-camera/background-audio?f=255&MSPPError=-2147217396" rel="nofollow">this tutorial</a> to set up the background audio player in my app but I'm stuck at step one. There is no capability called <code>Background Audio Task</code> in my manifest file. Adding it manually doesn't do any good either since these events described in another step aren't even available/shown in properties window/shown by IntelliSense.</p>
<p>Am I doing something wrong?</p>
| <p>I thought that page was fairly straightforward. As mentioned on the page, the capability is "Background Media Playback".</p>
<p><a href="https://i.stack.imgur.com/gUGIp.png" rel="nofollow"><img src="https://i.stack.imgur.com/gUGIp.png" alt="Screenshot"></a></p>
<p>If you still don't see <em>that</em> in the list, then it's probably because you do not have the Anniversay SDK (version 14393) or later installed. The Anniversary update introduced a new <a href="https://blogs.windows.com/buildingapps/2016/06/07/background-activity-with-the-single-process-model/" rel="nofollow">single process model</a> for background execution, which that webpage is walking you through.</p>
|
How do I remove the circular dependency in my Organization-Owner-Member models? <p>Heyo, I'm fairly new to this stuff so please pardon me if this is a stupid question.
I'm trying to create an app where users can create organizations and join already existing ones. My requirements are:</p>
<ul>
<li>an organization may have only one user designated the owner (the user who creates it)</li>
<li>users must be able to join several organizations</li>
<li>users must be able to create organizations and therefore be owners of multiple organizations</li>
</ul>
<p>So far I've got the following models.py:</p>
<pre><code>from django.db import models
from django.utils.translation import ugettext_lazy as _
from myapp.users.models import User
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Org(TimeStampedModel):
name = models.CharField(
_('Organization name'),
max_length=255,
)
owner = models.OneToOneField('OrgOwner')
members = models.ManyToManyField(
'OrgMember',
related_name='organization_members'
)
users = models.ManyToManyField(
User,
related_name='organization_users'
)
def __str__(self):
return self.name
class OrgMember(TimeStampedModel):
user = models.ForeignKey(
User,
related_name='user_profile'
)
organization = models.ForeignKey(
Org,
related_name='member_organization'
)
def __str__(self):
return self.user.username
class OrgOwner(TimeStampedModel):
member = models.OneToOneField(OrgMember)
organization = models.OneToOneField(Org)
def __str__(self):
return self.member.__str__()
</code></pre>
<p>My issue is that the way I've designed the models so far, I have a circular dependency. In order for a user to create an Org from scratch he needs to be an OrgMember of said, not yet created, Org. In other words, I cannot instantiate an OrgMember without assigning it an Org, but I cannot instantiate a new Org without an OrgOwner, for which I also need an OrgMember. </p>
<p>I'm sure there is just an error in my reasoning here. But perhaps there are some best practices for situations like this one you could share. There is probably a fairly simple solution to this, but I haven't been able to find one in an hour of searching and reading the django docs. Any help is much appreciated!</p>
| <p>I still can't see why you have so much looping information. Your <code>OrgMember</code> class has an organization field, even though <code>Org</code> already has a <code>ManyToMany</code> with <code>OrgMember</code>. Same thing with <code>OrgOwner</code> - except that points to <code>OrgMember</code> which already points to an <code>Org</code> as well. Both of those classes only have two fields - the <code>User</code> associated with it, and then the <code>Org</code>. Unless there are more fields, they serve no purpose - the same thing can be accomplished in one model:</p>
<pre><code>class Org(TimeStampedModel):
name = models.CharField(_('Organization name'), max_length=255)
# Only one owner, but each User can own more than one org
owner = models.ForeignKey('auth.User', related_name='owned_orgs')
members = models.ManyToManyField('auth.User', related_name='organization_members')
users = models.ManyToManyField(User, related_name='organization_users')
def __str__(self):
return self.name
</code></pre>
<p>I'd recommend that you do some more reading <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#module-django.db.models.fields.related" rel="nofollow">about Django's relationship fields</a></p>
|
How to create a String instead of printing it to standard out? <p>Consider the following function:</p>
<pre><code>use std::io;
pub fn hello() {
println!("Hello, How are you doing? What's your characters name?");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read name. What was that name again?");
println!("Welcome to the castle {}", name);
}
</code></pre>
<p>How do I take the last <code>println!</code> and turn it into a <code>"Welcome to the castle {}".to_string();</code> and have the <code>{}</code> replaced with <code>name</code> (obviously I would need to add <code>-> String</code> to the function declaration.)</p>
| <p>Use the <a href="https://doc.rust-lang.org/stable/std/macro.format!.html"><code>format!</code></a> macro.</p>
<pre><code>pub fn hello() -> String {
println!("Hello, How are you doing? What's your characters name?");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read name. What was that name again?");
format!("Welcome to the castle {}", name)
}
</code></pre>
|
Find Maximum value of a distribution <p>Question: I have a function <code>X</code>, and want to find the value <code>y</code> that maximizes <code>X(y)</code>.</p>
<pre><code>set.seed(8)
A <- seq (1:20)
B <- c(0,rbinom(18,1,0.5),1)
X <- function (y) {
fx <- prod(1*B-pnorm(A-y)*(-1)^B)
fx
}
X(10)
[1] 3.615998e-40
X(11)
[1] 5.624095e-53
</code></pre>
<p>I know I can loop through <code>X(0)</code> to <code>X(20)</code>, but it is very time consuming. Is there a smarter way to do want I need?</p>
| <p><code>optimize()</code> converges to the maximum value in the interval:</p>
<pre><code>optimize(X,c(0,20),maximum=TRUE)
## $maximum
## [1] 19.99993
##
## $objective
## [1] 0
</code></pre>
<p>Plotting the curve confirms this.</p>
<pre><code>x <- seq(0,20,length=1000)
y <- sapply(x,X)
plot(x,y,type="l")
</code></pre>
<p><a href="https://i.stack.imgur.com/lt93E.png" rel="nofollow"><img src="https://i.stack.imgur.com/lt93E.png" alt="enter image description here"></a></p>
|
Slide Up Transition of React Component <p>I am just starting to use animations/transition in my <code>React.js</code> projects. In the GIF below, when I close a <code>Message</code> component, it fades out. After it fades, I hide the component using <code>onAnimationEnd</code>.</p>
<p>What I want to happen is when a <code>Message</code> disappears have the below Components slide up. I am unsure conceptually how I would accomplish this either via a CSS animation/transition or via a React specific way. </p>
<p><a href="https://i.stack.imgur.com/zfRQI.gif" rel="nofollow"><img src="https://i.stack.imgur.com/zfRQI.gif" alt="enter image description here"></a></p>
<p><strong>Message.js</strong></p>
<pre><code>import React, {PropTypes, Component} from 'react';
import MessageTypes from '../constants/MessageTypes';
export default class Message extends Component {
constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
this.onAnimationEnd = this.onAnimationEnd.bind(this);
this.state = {
animate: false,
hide: false
}
}
handleClick(e) {
e.preventDefault();
this.setState({animate: true});
}
onAnimationEnd() {
console.log('fdsfd');
this.setState({hide: true});
}
render() {
return (
<div ref="message" onAnimationEnd={this.onAnimationEnd} className={`card message ${this.state.hide ? 'hide open' : ''} ${this.state.animate ? 'message-transition-fade-out' : ''}`}>
<span className={`icon icon-${this.iconLevel()}`} style={{color: `#${this.iconColor()}`}}></span>
<p>
<strong>{this.props.title}</strong><br />
<span dangerouslySetInnerHTML={{ __html: this.props.message }} />
</p>
<a href="#" onClick={this.handleClick}>
<span className="icon icon-close"></span>
</a>
</div>
);
}
}
</code></pre>
<p><strong>Message.scss</strong></p>
<pre><code>.message {
max-height: 150px;
transition: height 2s ease;
&.open {
height: 0; //define your height or use max-height
}
&-transition {
&-fade-out {
@include animation(0s, .3s, fadeout);
}
}
}
</code></pre>
| <p>I would suggest you to use <code>css transitions</code>. </p>
<p>Have a class called <code>open</code> attached to the root of the <code>Message</code> component. <code>onAnimationEnd</code> remove the class <code>open</code>. Now, use <code>height</code> to animate that class.</p>
<p>Pseudo code.</p>
<pre><code>.message {
height: 0px;
transition: height 0.3s ease;
}
.message.open {
height: 100px; //define your height or use max-height
}
</code></pre>
|
SQL Server: Determining games made more than 2 years ago <p>The question I have is Which developers have games that were released more than two years ago?</p>
<p>My code looks like this:</p>
<pre><code>SELECT
devName
FROM DEVELOPER as d
INNER JOIN GAME as g ON d.devID = g.devID
WHERE gameReleaseDate < (WHAT GOES HERE?);
</code></pre>
<p>I'm unsure how to properly have it find games released more than two years ago, I'm most likely failing to remember something very basic I dont want the answer just how to determine if something is below a certain amount of years.</p>
| <p>I think something like this should work (assuming that the field being compared is one of the <code>DATE</code> / <code>DATETIME</code> data types):</p>
<pre><code>DATEADD(year, -2, GETDATE())
</code></pre>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/sql-server/1471/dates/15054/dateadd-for-adding-and-subtracting-time-periods#t=201610160255445173715">DATEADD Example in Docs</a></p>
<p><a href="https://msdn.microsoft.com/en-us/library/ms186819.aspx" rel="nofollow">DATEADD on MSDN</a></p>
|
Initializing a char array with values in C cause Segmentation Fault <p>I have an array of <code>char</code> defined as followed</p>
<pre><code>char users[5] = "";
</code></pre>
<p>I then add users to this array by assignment as follow</p>
<pre><code>users[0] = "UserOne";
users[1] = "UserTwo";
</code></pre>
<p>However, my program crashes with a <code>Segmentation Fault</code>. </p>
<p>I have looked this up online and it seems to be memory related. I tried to search for a post talking about allocating memory and have found <code>malloc</code>. However, I am a little confused with the <code>malloc</code> function. </p>
<p>I have tried to allocate memory to my char array using </p>
<pre><code>users = malloc(sizeof(char));
</code></pre>
<p>Can someone explain to me what I am doing wrong?</p>
| <p>A char is a single character.</p>
<pre><code>char* user[5];
</code></pre>
<p>would be the right way to create an array of pointers to char arrays(strings).</p>
<p>I don't know the purpose of the <code>= ""</code> in the user declaration, but it should be an error. You could do</p>
<pre><code>char* user[5] = { "", "userOne", "userTwo", "", "" };
</code></pre>
|
Moving nodes within a Dijit Tree <p>I am using a tree as an input tool to allow the user to organize categories.</p>
<p>I would like the users to be able to move the nodes around at the top level, specifically reordering them under the same parent.</p>
<p>Everything looks fine until it is time for the store to be updated - the display is wrong - the moved item is not shown in the right place.</p>
<pre><code>require([
"dojo/aspect",
"dojo/store/Memory",
"dojo/store/Observable",
"dijit/Tree",
"dijit/tree/ObjectStoreModel",
"dijit/tree/dndSource",
"dojo/domReady!"
], function(aspect, Memory, Observable, Tree, ObjectStoreModel, dndSource) {
var observableStore, model;
var memoryStore = new Memory({
data: [{
"id": 10,
"position": 0,
"name": "top",
"parent": null
}, {
"id": 19,
"position": 18,
"name": "Audio",
"parent": 10
}, {
"id": 23,
"position": 19,
"name": "Monitors",
"parent": 10
}, {
"id": 20,
"position": 20,
"name": "Communication",
"parent": 10
}, {
"id": 21,
"position": 28,
"name": "Video",
"parent": 10
}, {
"id": 18,
"position": 29,
"name": "Camera",
"parent": 10
}, {
"id": 22,
"position": 40,
"name": "Five",
"parent": 21
}, {
"id": 24,
"position": 60,
"name": "Networking",
"parent": 21
}, {
"id": 25,
"position": 70,
"name": "Toasters",
"parent": 18
}],
mayHaveChildren: function(object) {
var children = this.store.getChildren(object);
return children.length > 0;
},
getChildren: function (object) {
return this.query({parent: object.id});
}
});
observableStore = new Observable(memoryStore);
model = new ObjectStoreModel({
store: observableStore,
query: {
name: "top"
}
});
aspect.around(memoryStore, "put", function(originalPut) {
// To support DnD, the store must support put(child, {parent: parent}).
// Since memory store doesn't, we hack it.
// Since our store is relational, that just amounts to setting child.parent
// to the parent's id.
return function(obj, options) {
if (options && options.parent) {
obj.parent = options.parent.id;
}
return originalPut.call(memoryStore, obj, options);
}
});
var tree =new Tree({
model: model,
dndController: dndSource,
betweenThreshold: 5,
showRoot: false,
persist: false
}, "category-tree").startup();
});
</code></pre>
<p><a href="https://jsfiddle.net/3b2ghzsq/1/" rel="nofollow" title="jsfiddle">JSFiddle</a></p>
<p><a href="https://bugs.dojotoolkit.org/ticket/18142" rel="nofollow">https://bugs.dojotoolkit.org/ticket/18142</a> - I could invest more time in this, but I don't want to. Choosing a different approach - using traditional inputs and providing a read-only tree view.</p>
| <p>You need to place the aspect around the store's put function before wrapping it with Observable. With your code Observable hasn't got access to the replaced put function. It will work if you replicate closely the <a href="https://dojotoolkit.org/reference-guide/1.10/dijit/Tree.html#drag-and-drop" rel="nofollow">example</a>.</p>
<pre><code>require([
"dojo/aspect",
"dojo/store/Memory",
"dojo/store/Observable",
"dijit/Tree",
"dijit/tree/ObjectStoreModel",
"dijit/tree/dndSource",
"dojo/domReady!"
], function(aspect, Memory, Observable, Tree, ObjectStoreModel, dndSource) {
var observableStore, model;
var memoryStore = new Memory({
data: [{
"id": 10,
"position": 0,
"name": "top",
"parent": null
}, {
"id": 19,
"position": 18,
"name": "Audio",
"parent": 10
}, {
"id": 23,
"position": 19,
"name": "Monitors",
"parent": 10
}, {
"id": 20,
"position": 20,
"name": "Communication",
"parent": 10
}, {
"id": 21,
"position": 28,
"name": "Video",
"parent": 10
}, {
"id": 18,
"position": 29,
"name": "Camera",
"parent": 10
}, {
"id": 22,
"position": 40,
"name": "Five",
"parent": 21
}, {
"id": 24,
"position": 60,
"name": "Networking",
"parent": 21
}, {
"id": 25,
"position": 70,
"name": "Toasters",
"parent": 18
}],
mayHaveChildren: function(object) {
var children = this.store.getChildren(object);
return children.length > 0;
},
getChildren: function (object) {
return this.query({parent: object.id});
}
});
aspect.around(memoryStore, "put", function(originalPut) {
// To support DnD, the store must support put(child, {parent: parent}).
// Since memory store doesn't, we hack it.
// Since our store is relational, that just amounts to setting child.parent
// to the parent's id.
return function(obj, options) {
if (options && options.parent) {
obj.parent = options.parent.id;
}
return originalPut.call(memoryStore, obj, options);
}
});
observableStore = new Observable(memoryStore);
model = new ObjectStoreModel({
store: observableStore,
query: {
name: "top"
}
});
var tree =new Tree({
model: model,
dndController: dndSource,
showRoot: false,
persist: false
}, "category-tree").startup();
});
</code></pre>
<p>A fork of your <a href="https://jsfiddle.net/pgianna/3gw8s0d1/1/" rel="nofollow">JSFiddle</a>.</p>
<p><strong>UPDATE</strong>: The above solution does not support the betweenThreshold option (the ability to drop an item in between others instead of making it a child of another item). Even the official reference guide example does not work. This needs a store that properly supports positioning of items (MemoryStore doesn't and the hack for the put function is not enough). One option is to fall back on the deprecated dojo/data/ItemFileWriteStore.</p>
<pre><code>require([
"dojo/data/ItemFileWriteStore",
"dijit/Tree",
"dijit/tree/TreeStoreModel",
"dijit/tree/dndSource",
"dojo/domReady!"
], function(ItemFileWriteStore, Tree, TreeStoreModel, dndSource) {
var model;
var categories = {
identifier: 'id',
label: 'name',
items: [
{ id: '0', name:'Foods', numberOfItems:1, children:[ {_reference: '1'}, {_reference: '2'}, {_reference: '3'} ] },
{ id: '1', name:'Fruits', numberOfItems:1, children:[ {_reference: '4'} ] },
{ id: '4',name:'Citrus', numberOfItems:1, items:[ {_reference: '5'} ] },
{ id: '5', name:'Orange'},
{ id: '2', name:'Vegetables', numberOfItems:0},
{ id: '3', name:'Cereals', numberOfItems:0}
]
};
var memoryStore = new ItemFileWriteStore({data: categories});
var model = new TreeStoreModel({store: memoryStore, query:{id: "0"}});
var tree =new Tree({
model: model,
dndController: dndSource,
betweenThreshold: 5,
showRoot: false,
persist: false
}, "category-tree").startup();
});
</code></pre>
<p>Here is another <a href="https://jsfiddle.net/pgianna/aop9jeo3/1/" rel="nofollow">JSFiddle</a>. You can also refer to this <a href="http://download.dojotoolkit.org/release-1.7.1/dojo-release-1.7.1/dijit/tests/tree/test_Tree_DnD.html" rel="nofollow">example</a>.</p>
|
strange behavior of enable_if <p>does anyone know why the following code compiles</p>
<pre><code>static const size_t CONSTANT = /* ... */;
template< size_t M = CONSTANT, typename std::enable_if_t< M!=1, size_t > = 0 >
res_type</*...*/> foo()
{
// ...
}
</code></pre>
<p>while this does not:</p>
<pre><code>static const size_t CONSTANT = /* ... */;
template< typename std::enable_if_t< CONSTANT!=1, size_t > = 0 >
res_type</*...*/> foo()
{
// ...
}
</code></pre>
<p>Many thanks in advance.</p>
<p>Best</p>
| <p>SFINAE requires the failed substitution to be dependant on a template parameter. </p>
<p>If the substitution failure happens at the first phase of the lookup (in other words, when it is not dependant on template parameters) the program is ill-formed, no diagnostics required. But the popular compilers yield a readable error in this case. </p>
<p>Otherwise the compiler must wait for the instantiation of the template specialization to know whether substitution can take place. If it cannot, it is required by the language not to produce a hard error, but be silently ignored instead.</p>
|
JSch SCP file transfer using "exec" channel <p>I'm very new to the SCP protocol and JSch. I have to transfer a file fro a remote device via SCP to Android. The server side developers refused to tell be anything about their device except for the file location, and the root account which can be used to access it with SCP.</p>
<p>Here are the steps I tried.</p>
<ol>
<li><p>Confirm that using JSch, my Android client can establish connection with the server. [complete]</p></li>
<li><p>Confirm that using JSch, and the <code>ChannelExec</code> object, I can send the <code>ls</code> command and read its output. [complete]</p></li>
<li><p>Confirm that using JSch, and the <code>ChannelSFTP</code> object, I can transfer a file from the device. [failed]</p></li>
</ol>
<p>The reason why (3) failed seems that the device (server) is not configured for SFTP. The maker keeps on saying that commands on ssh like below works:</p>
<pre class="lang-none prettyprint-override"><code>scp root@192.168.5.1/usr/WS026.jpeg [targetPath]
</code></pre>
<p>They say that the above command will copy the first parameter to the target path of the client. So, alternative to using the SFTP, <b>how can I implement that in JSch channel "exec"?</b></p>
| <p>If the device supports SCP only, do not try to use SFTP, use SCP.</p>
<p>There's an official example for implementing the SCP download using the JSch:<br>
<a href="http://www.jcraft.com/jsch/examples/ScpFrom.java.html" rel="nofollow">http://www.jcraft.com/jsch/examples/ScpFrom.java.html</a></p>
<hr>
<p>Do not get confused by the call of <code>scp</code> in the example code. That's how SCP protocol works. A local (OpenSSH) <code>scp</code> executes the <code>scp</code> on the remote server (with specific <em>non-public</em> arguments, in this case the <code>-f</code>) and then the two instances talk to each other. The example implements the local <code>scp</code>. The arguments used for the remote <code>scp</code> are not the arguments you would use for the local <code>scp</code>.</p>
<p>See also <a href="http://stackoverflow.com/q/26220381/850848">Explanation for SCP protocol implementation in JSch library</a>.</p>
|
loop within a loop in javascript <p>I am trying to run a loop inside a loop to get some valid dates but doesnt seem to work fine. my sample data is like</p>
<p>these are valid days
<code>[ 'Monday', 'Thursday', 'Friday', 'Sunday' ]</code></p>
<p>and these are valid dates</p>
<pre><code>[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Tue Oct 11 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Wed Oct 12 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sat Oct 15 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]
</code></pre>
<p>What I want to do is: find only those dates on which are equal to vaid days</p>
<p>What am doing is:</p>
<pre><code>_valid_dates = (dates, days) ->
validDates = dates
dates.forEach (date) ->
days.forEach (day) ->
if moment_strf(date).strftime("%A") != day
validDates.remove date
else
console.log "Am valid day", moment_strf(date).strftime("%A")
validDates
</code></pre>
<p>But the results are not coming as I am expecting. According to data the remaining dates should be</p>
<pre><code>[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]
</code></pre>
<p>Any help will be appreciated! Thanks</p>
| <p>You can do it simply using only javascript:</p>
<p>Instead of taking full names in day array you can use 0-6 for days and then</p>
<pre><code> //sunday=0,monday=1 ....saturday=6
var days=[1,4,5,0];
var result_arr=[]; // required array for result
for(date in dates)
{
if(days.indexOf(new Date(date).getDay())!=-1)
{
result_arr.push(date);
}
}
</code></pre>
|
Add multiple UIButtons with color images programmatically to the UIViewController scene <p>I have UIViewController class in which I add multiple color buttons programmatically to the scene. I have 11 different colors, so 11 UIButtons which I add to the scene in viewDidLoad function. See below how I add gray and red color buttons. Then I use function crayonsPressed action to select colors by tag. I do this way because UIButton selection depends on the tag value. As you can see this dependence by UIButton tag value, adding buttons this way in not good approach. I was wondering what would be the best way to programmatically add these 11 color buttons to the scene so that I don't have to repeat below code in viewDidLoad 11 times. My plan is to subclass this UIViewController to 11 more scenes in which they all will have same functionality for all 11 buttons, which is drawing.</p>
<p>Edited to load all image buttons with an array. Still need resolution on how to handle UIButton tag, so that when color button is pressed that color is selected.</p>
<pre><code>class ViewController: UIViewController {
let colors: [(CGFloat, CGFloat, CGFloat)] = [
(0, 0, 0),
(105.0 / 255.0, 105.0 / 255.0, 105.0 / 255.0),
(1.0, 0, 0),
(0, 0, 1.0),
(51.0 / 255.0, 204.0 / 255.0, 1.0),
(102.0 / 255.0, 204.0 / 255.0, 0),
(102.0 / 255.0, 1.0, 0),
(160.0 / 255.0, 82.0 / 255.0, 45.0 / 255.0),
(1.0, 102.0 / 255.0, 0),
(1.0, 1.0, 0),
(1.0, 1.0, 1.0),
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let arrayImages : [UIImage] = [UIImage(named: "Grey")!,
UIImage(named: "Red")!,
UIImage(named: "Black")!,
UIImage(named: "Blue")!,
UIImage(named: "Brown")!,
UIImage(named: "DarkGreen")!,
UIImage(named: "DarkOrange")!,
UIImage(named: "Grey")!,
UIImage(named: "LightBlue")!,
UIImage(named: "LightGreen")!,
UIImage(named: "Yellow")!]
var buttonX : CGFloat = 374.5
for images in arrayImages {
let imageButton = UIButton(frame: CGRect(x: buttonX, y: 643, width: 25, height: 125))
buttonX = buttonX + 25
imageButton.setImage(images, for: UIControlState.normal)
imageButton.addTarget(self, action: #selector(crayonsPressed(_:)), for: .touchUpInside)
self.view.addSubview(imageButton)
}
func crayonsPressed(_ sender: AnyObject) {
var index = sender.tag ?? 0
if index < 0 || index >= colors.count {
index = 0
}
(red, green, blue) = colors[index]
if index == colors.count - 1 {
opacity = 1.0
}
}
}
</code></pre>
| <p>As rightly suggested by @rmaddy to put the colours in an array and then use those colours in a loop. You may use a variable to keep track of the position of your array.</p>
<pre><code>var i = 0
for images in arrayImages {
let imageButton = UIButton(frame: CGRect(x: buttonX, y: 643, width: 25, height: 125))
buttonX = buttonX + 25
imageButton.tag = i
imageButton.setImage(images, for: UIControlState.normal)
imageButton.addTarget(self, action: #selector(self.crayonsPressed(_:)), for: .touchUpInside)
self.view.addSubview(imageButton)
i += 1
}
</code></pre>
<p>Now each of your buttons will have a valid <code>tag</code> value.</p>
|
Unable to find class within a class capybara <p>My html code is :</p>
<pre><code><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
</code></pre>
<p>I tried: </p>
<pre><code>1. find(:xpath, "//span[@class='sr-only']").click
2. page.find('.sr-only',visible: false).click
</code></pre>
<p>but was not able to find element 'sr-only'. How to find it?</p>
<p>Exception I got is: </p>
<pre><code>Selenium::WebDriver::Error::ElementNotVisibleError:
element not visible
</code></pre>
<p><strong>Note</strong> Using chrome webdriver + selenium</p>
| <p>By default Capybara doesn't find non-visible elements (which anything with a class of 'sr-only' usually is), and even when you tell it find non-visible elements (through the visible: false (or :hidden/:all) option) you won't be able to click on the element because there would be no way for a user to click on a non-visible option. It seems like you want to click on the close button, so if you're using Capybara 2.10+ you should be able to do </p>
<pre><code>click_button(class: 'close')
</code></pre>
<p>if using an older Capybara you should be able to do</p>
<pre><code>find('button.close').click
</code></pre>
|
My Reachability Notifier is only able to be called once <p>So, I have the following in my AppDelegate.<br>It will notify my when I turn my WIFI off but will not react after that initial run.<br>I have had this working in the past.<br>I'm on swift 3 with Xcode 8 and the reachability that is for this version of the swift and xCode.</p>
<p>I'm hoping to get a solution to this.<br><br>Thanks.</p>
<pre><code> var reachability: Reachability?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.reachability = Reachability()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
do {
try self.reachability?.startNotifier()
} catch {
print("Unable to start Notifier")
}
return true
}
func reachabilityChanged(_ note:Notification){
print("is in here")
let reachability = note.object as! Reachability
if reachability.isReachable{
print("is Reachable")
// self.amConnected.text = "YES"
//self.amConnected.fadeOut(duration: 2.0)
}else{
print("IsNotReachable")
//self.amConnected.text = "No"
//self.amConnected.fadeIn(duration: 2.0)
}
print("Changed status")
}
</code></pre>
| <p>There are some changes in Reachability in Swift 3. Download the latest <code>Reachability.swift</code> file and add that in your project. <a href="https://github.com/ashleymills/Reachability.swift/blob/master/Reachability/Reachability.swift" rel="nofollow">Link</a></p>
<p>For <strong>Swift 2.x</strong> code please check my answer <a href="http://stackoverflow.com/a/39984687/2545465">here</a></p>
<blockquote>
<p><strong>Swift 3.x code</strong></p>
</blockquote>
<p>Now in your <code>AppDelegate</code> take a <code>Reachability</code> class object</p>
<pre><code>private var reachability:Reachability!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//Network Reachability Notification check
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: ReachabilityChangedNotification, object: nil)
self.reachability = Reachability.init()
do {
try self.reachability.startNotifier()
} catch {
}
return true
}
</code></pre>
<p><code>reachabilityChanged</code> method defination</p>
<pre><code>//MARK:- Network Check
func reachabilityChanged(notification:Notification) {
let reachability = notification.object as! Reachability
if reachability.isReachable {
if reachability.isReachableViaWiFi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Network not reachable")
}
}
</code></pre>
<p>This will be always called whenever user switches from Wifi to Cellular and vice versa or when Network Connects and Disconnects and vice versa.<br> Working fine in my case.</p>
<p>Read the <a href="https://github.com/ashleymills/Reachability.swift#swift-3-breaking-changes" rel="nofollow">documentation</a> for more details in <strong>Swift 3 breaking changes</strong> section</p>
<p>Made a sample for you</p>
<p><a href="https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0" rel="nofollow">https://www.dropbox.com/sh/bph33b12tyc7fpd/AAD2pGbgW3UnqgQoe7MGPpKPa?dl=0</a></p>
|
Trying to make a simple Tic Tac Toe game in Javascript for an assignment. No errors, but nothing happens when I click the boxes <p>so I'm in a beginner web programming course, and my assignment is to make a Tic Tac Toe game in Javascript. My teacher provided a template for use to fill out, which should have been really simple. I've followed each instruction to the letter as best as I could, but I've run into a problem where nothing happens when I click the boxes. No errors or messages, nothing. Chrome isn't showing me any errors, so I have no idea where to even look. Could anyone point me in the right direction? I'm hoping that it's just silly beginner mistake. Here's what I have:</p>
<pre><code><html>
<head>
<!-- style settings-->
<style>
.tictac
{
background:purple;
border:#999 10px groove;
width:180px;
height:180px;
font-size:150px;
}
</style>
<script>
// create a variable for if the game is over, initialize it to false
var gameOver = false;
// create a variable for the current player, initialize it to 'O' or 'X'
// based on who will go first
if(confirm("Does X want to go first?") == true)
{
var player = 'X';
}
else
{
var player = 'O';
}
// create an array for the squares using the regular methodology
var squares = new Array();
squares[0] = 0;
squares[1] = 1;
squares[2] = 2;
squares[3] = 3;
squares[4] = 4;
squares[5] = 5;
squares[6] = 6;
squares[7] = 7;
squares[8] = 8;
// create a 2-d array of the win combinations, the data is as follows:
/*
0, 1, 2
3, 4, 5
6, 7, 8
0, 3, 6
1, 4, 7
2, 5, 8
0, 4, 8
2, 4, 6
*/
var winCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
// declare function named reset with no parameters
function reset()
{
// write a for loop starting at index 1 instead of the
// usual 0, that loops through all 9 positions
for (var i = 1; i < squares.length + 1; i++)
{
// create a variable to relate to each HTML button,
// set it equal to explicit text "sqr" concatenated
// with the looping variable of the for loop
var htmlButton = "sqr" + i;
// update the associated HTML element with the id
// equal to the variable created above, set it equal
// to and explicit empty string
}
// reset the global variable for the squares to an
// empty array using the literal methodology
squares = [];
// reset the global variable for the game being over
// setting it equal to false
gameOver = false;
}
//declare function named squareClick with parameter square
function squareClick(square)
{
// create a variable that is set equal to the HTML element
// with the id of square (i.e. the parameter) and retrieve its value
var idElement = document.getElementById(squares).value;
// this will be used down below as the id to update the HTML element
// create a variable that is set equal to the JavaScript method call
// parseInt() passing as an argument square.substring(3, 4),
// subtract one from the result of the parseInt method call
var parseSquare = ((parseInt(square.substring(3, 4))) - 1);
// this will represent the index of the array of squares where
// the user clicked
// write an if statement that evaluates if the variable
// value is equal to explicit string ""
if(idElement = "")
{
// update the HTML element using the parameter square as
// the id, setting its value equal to the global variable
// player
document.getElementById(square).value = player;
// in array of the squares update element stored at
// the index retrieved above to the global variable
// player
squares[index] = player;
}
// call the function checkForWinner passing as an argument
// the explicit value 'X'
checkForWinner('X');
// call the function checkForWinner passing as an argument
// the explicit value 'O'
checkForWinner('O');
// change the player
// write an if statement that checks if the player variable
// is equal to O, if true, set player to X
if(player == 'O')
player = 'X';
// write the else leg that switches player from X to O
else
player = 'O';
}
function playAgain()
{
// create a variable that stores the response to a
// confirm dialog box with text "Play again?"
var response = confirm("Play again?");
// write an if statement that evaluates the user's response
// from above compared to true
if (response == true)
{
alert("Let's play!");
reset ();
}
// write the else leg
else
{
alert("Thanks for playing!");
}
}
// declare function checkForWinner with one parameter called value
function checkForWinner(value)
{
// write for loop, start at index 0, loop while
// the index less than the length of the array
// winCombinations
for(var i = 0; i < winCombinations.length; i++)
{
// write an if statement that evaluates
// the squares array [] where the index is
// array winCombinations[][], with the first index
// being the looping variable and the second index
// being value 0, 1, or 2, checking if it is
// equal to the value parameter;
// this if statement should be
// three statements using the logical and &&
// e.g. squares[windCombinations[][]] == value &&
if(squares[winCombinations[i][0]] == value && squares[winCombinations[i][1]] == value && squares[winCombinations[i][2]] == value)
{
// display an alert dialog box stating which
// player won
alert(value + "won the game!");
// set the variable gameOver equal to true
gameOver == true;
}
}
// write an if statement checking if gameOver is true
if(gameOver == true)
{
// call function playAgain
playAgain();
}
// write the else leg
else
{
// use the return statement for program control
return("It's the next player's move!");
}
}
</script>
</head>
<body>
<table>
<tr>
<td><input type="button" id="sqr1" name="sqr1" class="tictac" onClick="squareClick('sqr1')" /></td>
<td><input type="button" id="sqr2" name="sqr2" class="tictac" onClick="squareClick('sqr2')" /></td>
<td><input type="button" id="sqr3" name="sqr3" class="tictac" onClick="squareClick('sqr3')" /></td>
</tr>
<tr>
<td><input type="button" id="sqr4" name="sqr4" class="tictac" onClick="squareClick('sqr4')" /></td>
<td><input type="button" id="sqr5" name="sqr5" class="tictac" onClick="squareClick('sqr5')" /></td>
<td><input type="button" id="sqr6" name="sqr6" class="tictac" onClick="squareClick('sqr6')" /></td>
</tr>
<tr>
<td><input type="button" id="sqr7" name="sqr7" class="tictac" onClick="squareClick('sqr7')" /></td>
<td><input type="button" id="sqr8" name="sqr8" class="tictac" onClick="squareClick('sqr8')" /></td>
<td><input type="button" id="sqr9" name="sqr9" class="tictac" onClick="squareClick('sqr9')" /></td>
</tr>
</table>
</body>
</html>
</code></pre>
| <p>This is a beginner question, so I'm going to post an answer appropriate to a beginner.</p>
<blockquote>
<p>No errors or messages, nothing. Chrome isn't showing me any errors, so I have no idea where to even look.</p>
</blockquote>
<p>You are correct that errors (you looked in Developer Tools > Console right?) are where to start.</p>
<p>The next thing you should do to find the error is <em>delete as much code as possible</em>. You have 9 squares? Make it 1. Replace as many functions as you can with very very simple definitions like <code>alert("This code ran");</code>.</p>
<p>Delete code until when you run it, the simpler behavior, like alerting "This code ran", starts happening.</p>
<p>Now you will have:</p>
<ol>
<li>A very small amount of code to work through, and/or</li>
<li>A very small amount of code that you added or removed that changed the behavior.</li>
</ol>
<p>Then research that. At that point you can probably google whatever you have trouble with and get an answer. You can post at StackOverflow if you are still stuck but I will warn you, <em>whatever mistake you are making has been asked here before.</em></p>
|
Center both the label and input in a page <p>I had tried to center the input boxes in a form using <code>margin: 0 auto</code>, and it worked. Problem is, since the input boxes were now block-level elements, the input boxes and labels were not aligned. They were on top of the other, like a line break. </p>
<p>So, I figured I could wrap each label and input box inside a div, and them do the same thing I did before: <code>margin: 0 auto</code>. Unfortunately, neither the input nor the label want to center now.</p>
<p>CSS 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>div.center{
margin: 0 auto;
display:block
}</code></pre>
</div>
</div>
</p>
<p>If you guys could help me, it would be great. I can also provide my full html code and css code if there is any need.</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>div.center {
display: inline-block;
border: solid;
}
form {
border: solid;
text-align: center
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<div class="center">Label</div>
<input type="text">
</form></code></pre>
</div>
</div>
</p>
|
Assembly + C - Sorting Structures <p>I'm working on a project that uses x86 Assembly (NASM) and C together. There's a subroutine written in Assembly that uses indexed addressing modes to figure out if a certain year (int) is lesser or greater than another, then returns -1, 1, or 0 depending on the outcome. It appears that if I input more than about 4 or 5 records, it doesn't sort properly. I've spent a few hours running it through gdb and figured out that on the last iteration of incrementing j for the first time (before i is incremented), it runs the swap even though it shouldn't, but I'm not sure how to fix it just yet. Thanks in advance for any thoughts.</p>
<p>---C code---</p>
| <p>I got it. It was because I was setting min = i in the wrong spot. It should be like this:</p>
<pre><code>for (i = 0; i < numBooks - 1; i++) {
/*** WAS HERE ***/
for (j = i + 1; j < numBooks; j++) {
/*** SHOULD BE HERE ***/
min = i;
/* Copy pointers to the two books to be compared into the
* global variables book1 and book2 for bookcmp() to see
*/
book1 = &books[i];
book2 = &books[j];
cmpResult = bookcmp();
/* bookcmp returns result in register EAX--above saves
* it into cmpResult */
/* book2 comes before book1, in other
words, book1 is greater - value stored in
eax will in this case be 1 */
if (cmpResult == 1) {
min = j;
}
if (min != i) {
tempBook = books[i];
books[i] = books[min];
books[min] = tempBook;
}
}
}
}
</code></pre>
|
How to detect fast moving soccer ball with OpenCV, Python, and Raspberry Pi? <p>This is the code. I am trying to detect different types of soccer ball using OpenCV and python. Soccer ball could of different colors. I can detect the ball if it is not moving. But, the code does not work if the ball is moving fast.</p>
<pre><code>from picamera.array import PiRGBArray
from picamera import PiCamerafrom picamera.array import PiRGBArray
from picamera import PiCamera
import time, cv2, sys, imutils, cv
import cv2.cv as cv
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (400, 300)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=(400, 300))
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = frame.array
img = cv2.medianBlur(image, 3)
imgg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#imgg = cv2.blur(imgg, (3,3))
#imgg = cv2.dilate(imgg, np.ones((5, 5)))
#imgg = cv2.GaussianBlur(imgg,(5,5),0)
circles = cv2.HoughCircles(imgg, cv.CV_HOUGH_GRADIENT, 1, 20, param1=100, param2=40, minRadius=5, maxRadius=90)
cv2.imshow("Frame", imgg)
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
if circles is None:
continue
for i in circles[0,:]:
cv2.circle(imgg,(i[0],i[1]),i[2],(0,255,0),1) # draw the outer circle
cv2.circle(imgg,(i[0],i[1]),2,(0,0,255),3) # draw the center of the circle
cv2.imshow("Framed", imgg)
</code></pre>
| <p>May I suggest you read this post?</p>
<p><a href="http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/" rel="nofollow">http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/</a> </p>
<p>There are also a few comments below indicating how to detect multiple balls rather than one.</p>
|
how make files training and testing in svm multi label? <p>how make files training and testing in svm multi label?
my question is <a href="https://www.quora.com/Can-anyone-give-me-some-pointers-for-using-SVM-for-user-recognition-using-keystroke-timing" rel="nofollow">https://www.quora.com/Can-anyone-give-me-some-pointers-for-using-SVM-for-user-recognition-using-keystroke-timing/answer/Chomba-Bupe?<strong>snid3</strong>=364610243&<strong>nsrc</strong>=1&<strong>filter</strong>=all</a></p>
<p>my project is dynamic keyboard, a user vs all user for training
For example if you have three classes A, B and C you will then have 3 SVMs each with its own parameters i.e weights and biases and 3 separate outputs corresponding to the 3 classes respectively. When training SVM-A the other two classes B and C act as negative training sets while A as positive, then when training SVM-B A and C are negative training sets and for SVM-C A and B are the negatives. This is the so called one vs all training procedure.</p>
<p>I try but the result goes wrong</p>
<p>my file to training is .csv and contains:</p>
<blockquote>
<p>65 134,+1</p>
<p>70 98,+1</p>
<p>73 69,+1</p>
<p>82 122,+1</p>
<p>82 95,+1</p>
<p>83 127,+1</p>
<p>84 7,+1</p>
<p>85 64,+1</p>
<p>65 123,-1</p>
<p>71 115,-1</p>
<p>73 154,-1</p>
<p>73 156,-1</p>
<p>77 164,-1</p>
<p>77 144,-1</p>
<p>79 112,-1</p>
<p>83 91,-1</p>
<p>and my file to testing is .csv and contents is:</p>
<p>65 111</p>
<p>68 88</p>
<p>70 103</p>
<p>73 89</p>
<p>82 111</p>
<p>82 79</p>
<p>83 112</p>
<p>84 36</p>
<p>85 71</p>
</blockquote>
<p>my code is </p>
<pre><code> 'use strict';
var so = require('stringify-object');
var Q = require('q');
var svm = require('../lib');
var trainingFile = './archivos/training/340.txt';
var testingFile = './archivos/present/340.txt';
var clf = new svm.CSVC({
gamma: 0.25,
c: 1, // allow you to evaluate several values during training
normalize: false,
reduce: false,
kFold: 1 // disable k-fold cross-validation
});
Q.all([
svm.read(trainingFile),
svm.read(testingFile)
]).spread(function (trainingSet, testingSet) {
return clf.train(trainingSet)
.progress(function(progress){
console.log('training progress: %d%', Math.round(progress*100));
})
.then(function () {
return clf.evaluate(testingSet);
});
}).done(function (evaluationReport) {
console.log('Accuracy against the testset:\n', so(evaluationReport));
});
enter code here
</code></pre>
| <p>Are your labels 1 and -1? If so, you will need to know those classes for your test data as well. The point of testing your classifier is to see how well it can predict unseen data. </p>
<p>As a small example you could build your classifier with your training data:
<code>x_train = [65, 134], [70,98]....... [79, 112], [83, 91]</code>
<code>y_train = [ 1, 1, ....-1, -1]</code></p>
<p>Then you test your classifier by passing in your test data. Say you pass in the first three examples in your test data and it makes the following predictions.
<code>[65, 111] --> 1</code>
<code>[68, 88] -->-1</code>
<code>[70,103] -->-1</code>
You then tally up how many pieces of test data it predicted right, but in order to do that you need to know the classes of your test data to begin with. If you don't have that, perhaps you want to try cross-validation on your training data.</p>
|
Using liftA2 with functions <p>I am wondering how this works. </p>
<pre><code>x 9001 = True
x _ = False
g 42 = True
g _ = False
(liftA2 (||) x g) 42 = True
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
x :: (Eq a, Num a) => a -> Bool
g :: (Eq a, Num a) => a -> Bool
</code></pre>
<p>How does the type of x and g (a -> Bool) correspond to what liftA2 expects (f a)?</p>
| <p>Remember that <code>((->) a)</code> is a <code>Monad</code> (also known as the reader monad), and hence an <code>Applicative</code> too. Taken <a href="https://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.Base.html#line-641" rel="nofollow">from the source for base</a></p>
<pre><code>instance Applicative ((->) a) where
pure = const
(<*>) f g x = f x (g x)
</code></pre>
<p>Then, <code>liftA2 (||) x g</code> is the function of type <code>(Num a, Eq a) => a -> Bool</code> that checks if either of the results of applying the argument to <code>x</code> and <code>g</code> is <code>True</code>.</p>
|
What's wrong with my JPQL query? <p>I am trying to implement join but I am facing error. I have product table and store table. product table references store table through foreign key as shown below:</p>
<p><strong>Product.java</strong></p>
<pre><code>@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long pId;
private String model;
private String brand;
private byte[] image;
private Long price;
private String currency;
private String transmissionType;
private String fuelType;
@ManyToOne
@JoinColumn(name="storeId")
private Store store;
// ⦠getters and setters
}
</code></pre>
<p>Now, I show the <strong>Store.java</strong></p>
<pre><code>@Entity
public class Store {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long storeId;
private String locality;
private String city;
private String state;
private String zipCode;
private String phone;
// ⦠getters and setters
}
</code></pre>
<p>Now , I show the <strong>repository</strong></p>
<pre><code>public interface ProductRepo extends JpaRepository<Product, Long> {
@Query("select p from Product p join p.storeId s where p.storeId = s.storeId and s.city = :city")
public List<Product> findByCity(@Param("city") String city);
@Query("select p from Product p join p.storeId s where p.storeId = s.storeId and s.state = :state")
public List<Product> findByState(@Param("state") String state);
}
</code></pre>
<p>Now, the error comes due to the last two queries where I implement join. What i want to do is get all products whose store is in particular city or state as you can see above.</p>
<p>The error I encounter is :</p>
<blockquote>
<p>Error starting ApplicationContext. To display the auto-configuration
report re-run your application with 'debug' enabled. 2016-10-16
09:53:25.203 ERROR 16132 --- [ main]
o.s.boot.SpringApplication : Application startup failed</p>
<p>org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'catalogueServiceController':
Unsatisfied dependency expressed through field 'productRepo'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productRepo': Invocation of init method
failed; nested exception is java.lang.IllegalArgumentException:
Validation failed for query for method public abstract java.util.List
com.practice.rest.assignment1.repository.ProductRepo.findByCity(java.lang.String)!
and so on ....</p>
</blockquote>
<p>What is the error in my query ?</p>
| <p>The query is invalid. You refer to a <code>p.storeId</code> which doesn't exist. I think something like this should be sufficient:</p>
<pre><code>select p from Product where p.store.city = :city
</code></pre>
<p>Or:</p>
<pre><code>select p from Product join p.store as store where store.city = :city
</code></pre>
<p>The upper should be sufficient as your JPA provider should be able to do the right thing for you then. The latter might be preferred if you want to be more specific about the join type to optimize the query.</p>
<p>The same applies to the other query. For future reference: everything you cut off the exception stack trace would've been the interesting part í ½í¸. If persistence providers reject JPQL, they're usually very specific about the error they encounter. So you should be able to find something around <code>p.storeId</code> being an invalid reference somewhere deeper down the stack trace actually.</p>
|
AUTO_INCREMENT & NOT NULL are not necessary after PRIMARY KEY (alone it's sufficient)? <p>I <del>know</del> <em><strong>Think</strong></em> that PRIMARY KEYs have to be <s>AUTO_INCREMENT</s> & NOT NULL ,,, but do i have to define them myself?
<br/>
P.S.: is the answer affected by the DBMS I'm using ?!</p>
<p><i></p>
<h3> Edited ! </h3>
<ul>
<li><strong>sorry I wasn't fully aware of this</strong> => "AUTO_INCREMENT does mean it has to be UNIQUE but it's not the other way around!".
<br /></li>
<li>Entity integrity constraint => No primary key value can be null.
<br /></li>
<li>A PRIMARY KEY constraint => automatically has a UNIQUE constraint defined on it.
</i></li>
</ul>
| <p>Primary key doesn't have to be auto_increment (or some equivalent in other engines).</p>
<p>It doesn't have to be defined as NOT NULL either.</p>
<p>The PRIMARY INDEX enforces the NOT NULL check and will cause the INSERT to fail in case you try inserting NULL value. Unless the engine supports inserting NULL which I already saw too, but that's very non-standard.</p>
|
Nonewline python <p>I am trying to print random numbers using random , but when I try to print the output in one line using <code>end= " "</code> the output doesnt show anything until I break the program.</p>
<pre><code>import random
import time
while True:
x = random.randint(1,6)
print(x, end=" ")
time.sleep(1)
</code></pre>
<p>The out put is like this after I interrupt :</p>
<pre><code>C1 2 3 5 5 4 5 4 1 ---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
</code></pre>
| <p>You can disable buffering by passing <code>flush=True</code> to <code>print</code> function (in python3)</p>
<pre><code>print(x, end=" ", flush=True)
</code></pre>
|
insert operation in Binary tree error? <p>I am getting error in the insertion operation for the binary tree the question link is( <a href="https://www.hackerrank.com/challenges/binary-search-tree-insertion" rel="nofollow">https://www.hackerrank.com/challenges/binary-search-tree-insertion</a> )
my code is :</p>
<pre><code>insert(node * root, int value)
{
int x = 0;
node* r = root;
node* xx;
while(x==0)
{
while(value<r->data&&r->left!=NULL)
{
r=r->left;
}
if(value<r->data&&r->left == NULL)
{
xx->data = value;
r->left = xx;
break;
}
while(value>r->data && r->right!=NULL)
{
r = r->right;
}
if(value>r->data&& r->right == NULL)
{
xx->data = value;
r->right =xx;
break;
}
}
return root;
}
</code></pre>
<p>The error that I am getting from the hackerrank is as follows:</p>
<p>Wrong Answer!
Some possible errors:</p>
<ol>
<li>You returned a NULL value from the function. </li>
<li>There is a problem with your logic</li>
<li>You are printing some value from the function</li>
</ol>
| <p>For starters, you need to allocate a new node on each insertion.</p>
<p>Start your declaration like this:</p>
<pre><code>node* insert(node * root, int value)
{
node* xx = new node();
xx->left = NULL;
xx->right = NULL;
xx->data = value;
</code></pre>
|
Create a new instance of a generator in python <p>I am trying to scrape a page which has many links to pages which contain ads. What I am currently doing to navigate it is going to the first page with the list of ads and getting the link for the individual ads. After that, I check to make sure that I haven't scraped any of the links by pulling data from my database. The code below basically gets all the href attributes and joins them as a list. After, I crosscheck it against the the list of links I have stored in my database of pages I have already scraped. So basically it will return a list of the links I haven't scraped yet. </p>
<pre><code>@staticmethod
def _scrape_home_urls(driver):
home_url_list = list(home_tab.find_element_by_tag_name('a').get_attribute('href') for home_tab in driver.find_elements_by_css_selector('div[class^="nhs_HomeResItem clearfix"]'))
return (home_url for home_url in home_url_list if home_url not in(url[0] for url in NewHomeSource.outputDB()))
</code></pre>
<p>Once it scrapes all the links of that page, it goes to the next one. I tried to reuse it by calling _scrape_home_urls() again </p>
<pre><code> NewHomeSource.unique_home_list = NewHomeSource._scrape_home_urls(driver)
for x in xrange(0,limit):
try:
home_url = NewHomeSource.unique_home_list.next()
except StopIteration:
page_num = int(NewHomeSource.current_url[NewHomeSource.current_url.rfind('-')+1:]) + 1 #extract page number from url and gets next page by adding 1. example: /.../.../page-3
page_url = NewHomeSource.current_url[:NewHomeSource.current_url.rfind('-')+1] + str(page_num)
print page_url
driver.get(page_url)
NewHomeSource.current_url = driver.current_url
NewHomeSource.unique_home_list = NewHomeSource._scrape_home_urls(driver)
home_url = NewHomeSource.unique_home_list.next()
#and then I use the home_url to do some processing within the loop
</code></pre>
<p>Thanks in advance.</p>
| <p>It looks to me like your code would be a lot simpler if you put the logic that scrapes successive pages into a generator function. This would let you use <code>for</code> loops rather than messing around and calling <code>next</code> on the generator objects directly:</p>
<pre><code>def urls_gen(driver):
while True:
for url in NewHomeSource._scrape_home_urls(driver):
yield url
page_num = int(NewHomeSource.current_url[NewHomeSource.current_url.rfind('-')+1:]) + 1 #extract page number from url and gets next page by adding 1. example: /.../.../page-3
page_url = NewHomeSource.current_url[:NewHomeSource.current_url.rfind('-')+1] + str(page_num)
print page_url
driver.get(page_url)
NewHomeSource.current_url = driver.current_url
</code></pre>
<p>This will transparently skip over pages that don't have any unprocessed links. The generator function yields the url values indefinitely. To iterate on it with a limit like your old code did, use <code>enumerate</code> and <code>break</code> when the limit is reached:</p>
<pre><code>for i, home_url in urls_gen(driver):
if i == limit:
break
# do stuff with home_url here
</code></pre>
<p>I've not changed your code other than what was necessary to change the iteration. There are quite a few other things that could be improved however. For instance, using a shorter variable than <code>NewHomeSource.current_url</code> would make the lines of the that figure out the page number and then the next page's URL much more compact and readable. It's also not clear to me where that variable is initially set. If it's not used anywhere outside of this loop, it could easily be changed to a local variable in <code>urls_gen</code>.</p>
<p>Your <code>_scrape_home_urls</code> function is probably also very inefficient. It looks like it does a database query for every url it returns (not one lookup before checking all of the urls). Maybe that's what you want it to do, but I suspect it would be much faster done another way.</p>
|
Matching words and valid sub-words in elasticseach <p>I've been working with ElasticSearch within an existing code base for a few days, so I expect that the answer is easy once I know what I'm doing. I want to extend a search to yield the same results when I search with a compound word, like "eyewitness", or its component words separated by a whitespace, like "eye witness".</p>
<p>For example, I have a catalog of toy cars that includes both "firetruck" toys and "fire truck" toys. I would like to ensure that if someone searched on either of these terms, the results would include both the "firetruck" and the "fire truck" entries.</p>
<p>I attempted to do this at first with the "fuzziness" of a match, hoping that "fire truck" would be considered one transform away from "firetruck", but that does not work: ES fuzziness is per-word and will not add or remove whitespace characters as a valid transformation.</p>
<p>I know that I could do some brute-forcing before generating the query by trying to come up with additional search terms by breaking big words into smaller words and also joining smaller words into bigger words and checking all of them against a dictionary, but that falls apart pretty quickly when "fuzziness" and proper names are part of the task.</p>
<p>It seems like this is exactly the kind of thing that ES should do well, and that I simply don't have the right vocabulary yet for searching for the solution.</p>
<p>Thanks, everyone.</p>
| <p>there are two things you could could do:</p>
<ol>
<li>you could split words into their compounds, i.e. <code>firetruck</code> would be split into two tokens <code>fire</code> and <code>truck</code>, <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-compound-word-tokenfilter.html" rel="nofollow">see here</a></li>
<li>you could use n-grams, i.e. for 4 grams the original <code>firetruck</code> get split into the tokens <code>fire</code>, <code>iret</code>, <code>retr</code>, <code>etru</code>, <code>truc</code>, <code>ruck</code>. In queries, the scoring function helps you ending up with pretty decent results. Check out <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/ngrams-compound-words.html" rel="nofollow">this</a>.</li>
</ol>
<p>Always remember to do the same tokenization on both the analysis and the query side.</p>
<p>I would start with the ngrams and if that is not good enough you should go with the compounds and split them yourself - but that's a lot of work depending on the vocabulary you have under consideration.</p>
<p>hope the concepts and the links help, fricke</p>
|
infowindow is not updating with marker google maps <p>I am developing a web page for viewing vehicle locations using gps data.
I have make the back end working fine with the help of Mr. Aruna a genius in stack Overflow. Now I need a help for updating my google map infowindow. marker is updating its location no issue with that. while clicking it is not updating is current speed and another info according to that.
Below is the code in </p>
<pre><code>var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
var content = res[i].name + " S1: " + res[i].speed * 1.6 + '<br />' + "D: " + res[i].lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(res[i].id)) {
console.log('just move it...');
markerStore[res[i].id].setPosition(new google.maps.LatLng(res[i].position.lat, res[i].position.long));
//markerStore[res[i].id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[res[i].id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[res[i].id]);
};
})(markerStore[res[i].id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
title: res[i].name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(res[i].position.lat, res[i].position.long),
// title: res[i].name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[res[i].id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
</code></pre>
<p>Please help me ...</p>
| <p>Your <code>click</code> event listener is called asynchronously, long after your <code>for</code> loop has completed. So the value of <code>i</code> is not what you expect.</p>
<p>This is easy to fix (assuming there are not other problems as well).</p>
<p>Take all of the code inside the <code>for</code> loop body and make it a function. I'll call the function <code>addMarker( item )</code>, but of course you can use any name you want.</p>
<p>Everywhere you have <code>res[i]</code> in that function, change it to <code>item</code>. Then shorten the <code>for</code> loop so it contains only a single line: <code>addMarker( res[i] );</code>.</p>
<p>So now your code looks like this:</p>
<pre><code>var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
getMarkers();
function getMarkers() {
var infowindow = null;
$.get('/markers', {}, function (res, resp) {
console.dir(res);
for (var i = 0, len = res.length; i < len; i++) {
addMarker( res[i] );
}
function addMarker( item ) {
var content = item.name + " S1: " + item.speed * 1.6 + '<br />' + "D: " + item.lastupdate
infowindow = new google.maps.InfoWindow({
content: "A"
});
//Do we have this marker already?
if (markerStore.hasOwnProperty(item.id)) {
console.log('just move it...');
markerStore[item.id].setPosition(new google.maps.LatLng(item.position.lat, item.position.long));
//markerStore[item.id].setMap(map);
// Not sure below block and its not updating
google.maps.event.addListener(markerStore[item.id], 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, markerStore[item.id]);
};
})(markerStore[item.id], content, infowindow));
} else {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.position.lat, item.position.long),
title: item.name,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
//var marker = new google.maps.Marker({
// position: new google.maps.LatLng(item.position.lat, item.position.long),
// title: item.name,
// map: map
//});
//google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
// return function () {
// infowindow.setContent(content);
// infowindow.open(map, marker);
// };
//})(marker, content, infowindow));
markerStore[item.id] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}, "json");
}
</code></pre>
<p>I didn't check for any other errors in your code, but this will fix the specific problem you are asking about.</p>
<p>To learn more about this, read up on <a href="http://stackoverflow.com/search?q=javascript+closure">JavaScript closures</a>.</p>
|
How to detect if users are near each other - Swift <p>I know how to use region monitoring to trigger an event when a user enters or exits a certain region, however, I am if it is possible to do the same thing in case two (or more) users are near each other (around 100 meters from each other). </p>
<p>I'm afraid iBeacon is not what I need.</p>
<p>Is this is something that can be done through CloudKit maybe? I am confused after searching for an answer the whole night without any luck. I would really appreciate any help.</p>
<p>Thanks in advance. </p>
| <p>You can achieve this through <a href="https://developer.apple.com/reference/multipeerconnectivity" rel="nofollow">Apple's Multipeer Connectivity Framework</a>.</p>
<p>It is limited up to 7 other connected iOS devices at a time within 100 meters.</p>
<p>There's also a WWDC video on it here too <a href="https://developer.apple.com/videos/play/wwdc2013/708/" rel="nofollow">WWDC13</a>. </p>
|
Python - remainder operator <p>Although I know there is a built in <code>str()</code> <code>function</code> in <code>python</code>, I'm trying to understand its logic.</p>
<pre><code>def intToStr(i):
digits = '0123456789'
if i == 0:
return '0'
result = ''
while i > 0:
result = digits[i%10] + result
i = i/10
return result
</code></pre>
<p>what I don't get is the part in the <code>loop</code> where <code>[i%10]</code>. </p>
<p>How do I get a remainder when <code>i</code> <code><</code> <code>10</code>?</p>
| <p>% means mod, a number mod 10, result in the last number in it.<br>
So 5 % 10, you will get 5.<br>
You should try it yourself first.</p>
|
Merging numeric and characters from different datasets <p>I am trying to combine two datasets.
Dataset 1 has ca. 4000 rows and Dataset 2 has 132 rows. I want to match the <code>Brand</code> names in Dataset 2 with the <code>UPS</code> one in dataset 1. So All the <code>UPS</code> have the corresponding <code>Brands</code> in 1 as well. I tried to merge them both with <code>merge</code>. However, I have been so far unsuccessful of merging them.</p>
<p>DataSet 01:
Where UPS is numeric</p>
<pre><code> UPS WEEK AP
1 1111112016 1 385.22
2 1111112016 2 221.63
3 1111112016 3 317.47
4 1111112016 4 173.71
5 1111112016 5 269.55
</code></pre>
<p>Dataset 02:</p>
<pre><code> UPC Brand
1 1111112016 Dove
2 1111112440 Dove
3 1111112480 Dove
4 1111112501 Dove
5 1111132008 Lever
6 1111132012 Lever
7 1111132048 Lever
8 1111132122 Lever
</code></pre>
<p>This is how i tried it so far:</p>
<pre><code>Brand = c(unique(UB$Brand))
UPS = c(unique(PAW2$UPS))
PAWn = merge(PAW, UB, by.x = "UPS", by.y = "Brand")
</code></pre>
<p>I am aware that there are other posts out there. But so far they did not help.</p>
| <p>Based on your description, I think you need:</p>
<pre><code> merge(PAW, UB, by.x = "UPS", by.y = "UPC", all.x = TRUE)
</code></pre>
<p>to get what you want. As Nicola already said in the comments, the only way you can match the <code>Brand</code> names in <code>UB</code> to the <code>UPS</code> codes in <code>PAW</code> is via matching with the <code>UPC</code> codes in <code>UB</code>.</p>
<p>This also works when <code>UB$UPC</code> is a character variable and <code>PAW$UPS</code> is a numeric variable.</p>
<p>By adding <code>all.x = TRUE</code> all observations in <code>PAW</code> are returned, even when they don't have matching values in <code>UB</code>.</p>
|
Microsoft Graph Send Mail giving ErrorSubmissionQuotaExceeded <p>I am using Microsoft Graph API to send mails to users of a domain in which I am an admin. I have created a script for doing so. I am able to send some mails (around 10000) after which it returns an error </p>
<p>"ErrorSubmissionQuotaExceeded" and says please try after some time.</p>
<p>Is their a specific time after which I should try again ?</p>
<p>Is their a way to increase the quota (or by passing some parameter with the graph request so that it may delete the previous mails and refresh the quota) ?</p>
| <p>Transport within exchange limits the number of emails that a given account can send per minute. The default settings in O365 are 30 messages per minute. Try it again by limit your submission rate to 1 mail every 2 seconds. I'm not sure how it is calculated off the top of my head (per minute, per hour, per whatever), but start there and see if that solves your problem.</p>
|
how we cam make a sharp edge of div from middle in css? <p>I want to make a div with something like this.</p>
<p><a href="https://i.stack.imgur.com/8k9kz.png" rel="nofollow"><img src="https://i.stack.imgur.com/8k9kz.png" alt="enter image description here"></a></p>
<p>After twitter circle the edge is showing in middle. How can i make it? Please any one can help me. I try a lot but i am not succeed. Thanks</p>
| <p>Something like this ? </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>body {background:#FFFFFF;padding:20px}
p {background:black; -webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px; width:250px; height:50px}
.arrow_div{border:solid 10px transparent;border-right-color:#000;position:absolute;margin:-50px 0 0 -20px;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p></p>
<div class="arrow_div"></div></code></pre>
</div>
</div>
</p>
<p>change your div <strong>color</strong>, <strong>height</strong> , <strong>width</strong> , according to your need.</p>
|
Session not working after moving from 5.2 to 5.3 <p>When i move my site then controller don't get session available but get session view page. My previous version was laravel 5.2 to move laravel 5.3</p>
<p>Please can me help me any guys.</p>
| <p><strong>This is Directly from laravel docs, Upgrade guide from 5.2 to 5.3 :</strong></p>
<p><strong>Session In The Constructor</strong></p>
<p>In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.</p>
<p>As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:</p>
<pre><code><?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class ProjectController extends Controller
{
/**
* All of the current user's projects.
*/
protected $projects;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->projects = Auth::user()->projects;
return $next($request);
});
}
}
</code></pre>
<p>Of course, you may also access the request session data or authenticated user by type-hinting the Illuminate\Http\Request class on your controller action:</p>
<pre><code>/**
* Show all of the projects for the current user.
*
* @param \Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
$projects = $request->user()->projects;
$value = $request->session()->get('key');
//
}
</code></pre>
|
How to prevent page to scroll to top after gridview checkbox changed <p><a href="https://i.stack.imgur.com/G95zF.png" rel="nofollow">enter image description here</a>i tried many solutions before to prevent page scroll top after checkbox in grid view was changed but no one solve my problem .. please help!
thanks in advance</p>
<p>(update)--></p>
<h2>this is the Design code:</h2>
<pre><code> <asp:Panel ID="Panel2" runat="server" CssClass="Panel" GroupingText="<img src='Images/lightbulb.gif' /> Step 2: Seclect Threats to detect">
<%--<h1 style="text-align:right;padding-right:30px;position:absolute;right:40px;top:300px" > <asp:Label ID="lbl_cost" runat="server" Text="0 $" ></asp:Label></h1>--%>
<ajax:TabContainer ID="tc_thread_types" runat="server" AutoPostBack="true" Width="100%" CssClass="Tab" ActiveTabIndex="0">
<ajax:TabPanel ID="tab_mem_threads" runat="server" HeaderText="Member Threats" CssClass="Tab">
<ContentTemplate>
<div id="scrollDiv1" style="width: 100%; max-height: 400px; overflow: auto" >
<asp:GridView ID="gv_ThDetails_Mem" runat="server" CssClass="Grid"
Style="width: 100%; padding: 25px; margin-top: 10px; margin-bottom: 10px"
AutoGenerateColumns="False" OnRowDataBound="gv_ThDetails_mem_RowDataBound">
<Columns>
<asp:BoundField DataField="thread_id" HeaderText="Threat Id" />
<asp:BoundField DataField="thread_desc" HeaderText="Threat Description" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ch_all_mem" runat="server" AutoPostBack="true" OnCheckedChanged="ch_all_mem_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
&nbsp;&nbsp;&nbsp;
<%--<asp:CheckBox ID="cb_includedThreat_mem1" Onclick='<%# "ShowCurrentTime(" +Eval("serial") + " );" %>' runat="server" />--%>
<asp:CheckBox ID="cb_includedThreat_mem" runat="server" AutoPostBack="true" OnCheckedChanged="cb_includedThreat_mem_CheckedChanged" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="serial" HeaderText="serial" Visible="false" />
</Columns>
</asp:GridView>
</div>
<script type="text/javascript">
//var prm = Sys.WebForms.PageRequestManager.getInstance();
//prm.add_beginRequest(beginRequest);
//function beginRequest() {
// prm._scrollPosition = null;
//}
</script>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</code></pre>
<p></p>
<h2>And this is the code behind:</h2>
<pre><code>protected void cb_includedThreat_mem_CheckedChanged(object sender, EventArgs e)
{
try
{
//up_frdSetup.Update();
CheckBox included = (CheckBox)sender;
//GridViewRow gr = (GridViewRow)included.Parent.Parent;
int count;
if (rbl_memType.SelectedIndex == -1)
{
included.Checked = false;
SystemMsg.fn_SetMessageProperties("U6", "You should select membership first!"); // casting
SystemMsg.Focus();
return;
}
if (Session["IsExpired"] != null && Session["IsExpired"].ToString().Equals("Y") && rbl_memType.SelectedValue.ToString().Equals("T"))
{
included.Checked = false;
ib_save.Enabled = false;
// ib_save.CssClass = "btn disabled";
ib_save.ToolTip = "Submit was disabled As your trial version was expired!";
SystemMsg.fn_SetMessageProperties("U6", "Your trial version was expired! Please select Preimuim Subscription Now!");
//lbl_cln_msg.Text = "Your trial version was expired! Please select Premium Subscription Now!";
//cln_msg.Style.Add("display", "normal");
return;
}
if (ViewState["cnt_th_mem"] == null)
{
count = 0;
}
else
{
count = int.Parse(ViewState["cnt_th_mem"].ToString());
}
if (included.Checked)
{
count++;
ViewState["cnt_th_mem"] = count;
}
else if (!included.Checked && count > 0)
{
count--;
ViewState["cnt_th_mem"] = count;
}
included.Focus();
if (rbl_memType.SelectedValue.ToString().Equals("T"))
{
int tot_cnt = fn_check_tot_checked_threads();
if (tot_cnt > 3)
{
included.Checked = false;
count--;
ViewState["cnt_th_mem"] = count;
//lbl_cln_msg.Text = "The Maximum allowed threats in trial membership is Three only!";
//cln_msg.Style.Add("display", "normal");
SystemMsg.fn_SetMessageProperties("U6", "The Maximum allowed threats in trial membership is Three only!");
SystemMsg.Focus();
return;
}
//lbl_cost.Text = "0$";
//ViewState["cnt_th_mem"] = 0;
}
else if (rbl_memType.SelectedValue.ToString().Equals("P"))
{
//lbl_cost.Text = (Double.Parse(Session["th_price"].ToString()) * count) + "$";
ViewState["cnt_th_mem"] = count;
}
//fn_checkIncluded_Mem_Threads();
CheckBox ch_all = gv_ThDetails_Mem.HeaderRow.FindControl("ch_all_mem") as CheckBox;
if (count == gv_ThDetails_Mem.Rows.Count)
{
ch_all.Checked = true;
}
else if (count == 0)
{
ch_all.Checked = false;
}
else
{
ch_all.Checked = false;
}
fn_check_tot_cost();
}
catch (System.IO.IOException eio)
{
SystemMsg.fn_SetMessageProperties("S1", eio.Message); // IO
SystemMsg.Focus();
return;
}
catch (NullReferenceException ex)
{
SystemMsg.fn_SetMessageProperties("S2", ex.Message); // NULL
SystemMsg.Focus();
return;
}
catch (SqlException sqlEx)
{
SystemMsg.fn_SetMessageProperties("S4", sqlEx.Message); // SQL
SystemMsg.Focus();
return;
}
catch (Exception exe)
{
SystemMsg.fn_SetMessageProperties("S0", exe.Message);
SystemMsg.Focus();
return;
}
}
</code></pre>
<p>thanks in advance ..</p>
| <p>Put this in the page directive <strong><%@ Page %></strong></p>
<pre><code>MaintainScrollPositionOnPostback = "true"
</code></pre>
<p>It happens due to page PostBack. The above ensures the position of the scroll after page PostBack. </p>
<p>Or keep the <code>GridView</code> in a div and use <code>JavaScript</code> trick to do so: <a href="http://michaelsync.net/2006/06/30/maintain-scroll-position-of-div-using-javascript-aspnet-20" rel="nofollow">Maintain Scroll Position in Div</a></p>
|
Postgresql, Rails - could not fork autovacuum worker process: Resource temporarily unavailable <p>This is happening to me while in my local environment, Mac OSX, every time I start my server - puma - and workers - resque. </p>
<p>The logs don't say anything helpful, just a repeated, "could not fork autovacuum worker process: Resource temporarily unavailable."</p>
<p>Until I turn ctr-c out of the server, it locks up my entire computer. When I try to visit a site in the browser it just hangs, and when I open a new tab in the terminal it says, 'pipe broken' and closes it. The MAC console isn't spitting out anything helpful, at least from what I can tell. </p>
<p>Anyone have any thoughts to why this is?</p>
<p>I've restarted Postgres multiple times to no avail.</p>
<p>EDIT: </p>
<p>Log just started spitting out, 'LOG: could not fork new process for connection: Resource temporarily unavailable'</p>
<p>Puma thread count:</p>
<p><code>threads_count = ENV.fetch("RAILS_MAX_THREADS") { 10 }.to_i</code></p>
<p>DB: <code>pool: 100</code></p>
<p>EDIT2: </p>
<p>Tried to increase max_connection count from 100 to 200, still nothing. Ran into the duplicate postmaster.id error. Removed it, restarted Postgres, but still the same issue remains - cleared the postmaster.id error though.</p>
| <p>I followed these two articles, and so far this seems to work. Will update if something changes.</p>
<p><a href="https://github.com/sociam/indx/wiki/Increasing-max-connections-under-os-x" rel="nofollow">https://github.com/sociam/indx/wiki/Increasing-max-connections-under-os-x</a> </p>
<p><a href="http://big-elephants.com/2012-12/tuning-postgres-on-macos/" rel="nofollow">http://big-elephants.com/2012-12/tuning-postgres-on-macos/</a></p>
|
vim match for complete html tags <p>Helllaw world?</p>
<pre><code><font color=red><font color=red>I am stupid</font></font>
</code></pre>
<p>We can see that <code><font color=red></code> is duplicated, so I can delete it by a command</p>
<pre><code>:%s,<font color=red>\(<font color=red>[^<]*</font>\)</font>,\1,g
</code></pre>
<p>However, for the lines</p>
<pre><code><font color=red><font color=red>I am <b>stupid</b>, Huh.</font></font>
<font color=red><font color=red>I am <span style="something"><font color=blue>stupid</font>, Huh.</span></font></font>
</code></pre>
<p>The above command does not work.</p>
<p>So I imagined that I would be happy, if there were some escape character, for example '\Q', such that '\Q' matches any html tag complete words. Here, the tag complete words means that</p>
<pre><code>I am <b>stupid</b>, Huh.
I am <span style="something"><font color=blue>stupid</font>, Huh.</span>
I am <br> <font color=red><img src="me.html"></font> <br>
<u><a href="you.html">You</a></u> are <b><font color=red>smarter</font></b> than me
</code></pre>
<p>lines are tag complete words, because above four lines have no unmatched tags. All the opened tags are closed completely, by this reason, above four lines are tag complete words lines by my definition.</p>
<p>Then if I wanted to delete the leading tag <code><font color=red></code> for following line.</p>
<pre><code> <font color=red><font color=red>I am <b>stupid</b>, Huh.</font></font>
</code></pre>
<p>I can use the following command.</p>
<pre><code> :%s,<font color=red>\(<font color=red>\Q*</font>\)</font>,\1,g
</code></pre>
<p>Is there '\Q' like wild card in vim?</p>
<p>If '\Q' wild card exists, then by typing '/\Q' we can easily find unmatched tags (that is, not-closed tags and not-opened tags)</p>
| <p>Just for information. </p>
<p>I am the person who asked above original question.</p>
<p>I wrote following code.</p>
<pre><code>let g:position=[0,0,0,0]
function! SetQQ(arg_0, arg_1, arg_2, arg_3)
let g:position[0] = a:arg_0
let g:position[1] = a:arg_1
let g:position[2] = a:arg_2
let g:position[3] = a:arg_3
call setpos('.', g:position)
endfunction
let g:xxcmd_find_pair_escape = "normal vat\<ESC>"
let g:xxcmd_find_pair = "normal vat"
let g:xxcmd_escape_me = "normal \<Esc>"
let g:xxcmd_del_out = "normal hda>`<da>"
function! PairOnePrivate(command, pattern)
let xxcmd_onn="normal lda>"
let xxcmd_all="normal hdat"
let s:mycount=0
let curr_c = col(".")
let my_line = line(".")
let cmd_done = 0
while 1
let where_a = match(getline(my_line), a:pattern, curr_c - 1)
if (where_a < 0 )
echo "POP(): NOTHING and BREAK at=" getline(my_line)
break
endif
let next_search_position = matchend(getline(my_line), a:pattern, curr_c - 1)
call SetQQ(0, my_line, where_a+1, 0)
exec g:xxcmd_find_pair_escape
if ((my_line==line(".")) && (col(".") == where_a+1))
let curr_c = next_search_position
exec g:xxcmd_escape_me
exec xxcmd_onn
echo "POP(): XXX There is no matching tag at line " line(".")
break
endif
if (a:command == 0)
echo "POP(): DELETE ALL"
exec xxcmd_all
let cmd_done = 1
else
echo "POP(): DELETE OUTER"
exec g:xxcmd_del_out
let cmd_done = 1
endif
let s:mycount += 1
endwhile
return cmd_done
endfunction
function! PairOne(command, pattern)
let target = "<.[^>]*"
if (a:pattern !~ target)
echo "PairOne(): " a:pattern "args should begin with <"
return
endif
call PairOnePrivate(a:command, a:pattern)
endfunction
</code></pre>
<p>Whenever I wanted to delete <code><span></code> for following line,</p>
<pre><code>Something <span>something <b>Something</b> Something</span>
</code></pre>
<p>I used </p>
<pre><code>:g/<span>/call PairOne(1, @/)
</code></pre>
<p>I think I could find answer of my original question by changing the <code>PairOne()</code>. But I hate to code the <code>PairOne()</code>.</p>
|
python csv new line <p>iam using this code to convert db table to csv file, it is converting in to csv but instead of new line / line breck its using double quotes , can someone help me </p>
<pre><code>import MySQLdb
import csv
conn = MySQLdb.connect(user='root', db='users', host='localhost')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users.newusers')
ver = cursor.fetchall()
ver1 = []
for ve in ver:
ve = str(ve).replace("', '","|").replace(", '","|").replace(","," ").replace(" "," ").replace("|",",")
ver1.append(ve)
print ver1
csv_file = open('filename', 'wb')
writer = csv.writer(csv_file)
writer.writerow(ver1) csv_file.close()
</code></pre>
<p>current output </p>
<pre><code>"(114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes')","(115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes')"
</code></pre>
<p>expected out </p>
<pre><code> 114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes
115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes
</code></pre>
| <p>SQL queries will return results to you in a list of tuples from <code>fetchall()</code>. In your current approach, you iterate through this list but call <code>str()</code> on each tuple, thereby converting the whole tuple to its string representation.</p>
<p>Instead, you could use a list comprehension on each tuple both to get it into a nested list format and apply your <code>replace()</code> operations.</p>
<pre><code>for ve in ver:
ver1.append([str(item).replace(<something>) for item in ve])
</code></pre>
<p>In the final step you use <code>csv.writerow()</code> which is designed to be used within a <code>for</code> loop. If your list is nested in the form <code>[[row1], [row2]]</code> then you can just change this to writerow<strong>s</strong>. Also, it's best practice to use the context manager <code>with</code> to handle files as this will automatically close the file once the operation is completed.</p>
<pre><code>with open('filename.csv', 'wb') as csv_file:
writer = csv.writer(csv_file)
writer.writerows(ver1)
</code></pre>
|
Why it raises error when print the return values of function for non-linear equations <p>I use fsolve to solve equations, but when I put the solution into the KMV() function again, it raises an exception. I can not figure it out... </p>
<pre><code>def KMV(x, *args):
valueToEquity = float(x[0])
volOfValue = float(x[1])
equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity = args
d1 = (np.log(equityToDebt * equityToDebt) + (riskFreeRate + 0.5 * volOfEquity**0.5)
* TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
d2 = (np.log(abs(equityToDebt * equityToDebt)) + (riskFreeRate - 0.5 * volOfEquity**0.5)
* TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
f1 = valueToEquity * norm.cdf(d1) - np.exp(-riskFreeRate * TimeToMaturity) * norm.cdf(d2) / equityToDebt - 1
f2 = norm.cdf(d1) * valueToEquity * volOfValue - volOfEquity
return f1, f2
def solver():
equityToDebt = 1
volOfEquity = 0.2
riskFreeRate = 0.03
TimeToMaturity = 1
args = equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity
x0 = [1, 0.2]
sol = fsolve(KMV, x0, args=args)
print(sol)
</code></pre>
<p>The solutions I get is </p>
<pre><code>[ 1.29409904 0.17217742]
</code></pre>
<p>However if I use the following code:</p>
<pre><code>print(KMV(sol, args=args))
</code></pre>
<p>The exception is shown as below:</p>
<pre><code> print(KMV(sol, args = args))
TypeError: KMV() got an unexpected keyword argument 'args'
</code></pre>
<p>Then I changed into another way to call KMV():</p>
<pre><code>print(KMV(sol, args))
</code></pre>
<p>The exception is another one:</p>
<pre><code>ValueError: need more than 1 value to unpack
</code></pre>
| <p>If you remove the leading <code>*</code> from <code>args</code> in the declaration of <code>KVM</code> you can call it like that, but other code would fail if you did that. <code>*args</code> is for <em>variadic</em> functions, that is functions with a variable number of parameters. </p>
<p>If you want to pass keywords as well then pass a dictionary, often called <code>kwargs</code>. Note that the left-right order of these is critical. Here is a simple example:</p>
<pre><code>def KMV(x, *args, **kwargs):
if 'args' in kwargs:
args = kwargs['args'],
return args
args = 1,2,3,4
sol = 42
print(KMV(sol, args))
print(KMV(sol, args = args))
</code></pre>
|
Can't call CMake from a Python script <p>I'm trying to call the <a href="http://en.wikipedia.org/wiki/CMake" rel="nofollow">CMake</a> command from a Python script. This is my code:</p>
<pre><code>cmakeCmd = ["C:\Program Files\CMake\bin\cmake.exe",'-G Visual Studio 11 Win64', 'C:\Users\MyUser\Desktop\new\myProject']
retCode = subprocess.check_call(cmakeCmd, shell=True)
</code></pre>
<p>But I get the following output when running the script:</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
Traceback (most recent call last):
File "C:\Users\ochitaya\Desktop\New\myProj\sc.py", line 10, in <module>
retCode = subprocess.check_call(cmakeCmd, stderr=subprocess.STDOUT, shell=True)
File "C:\Python27\lib\subprocess.py", line 541, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['C:\\Program Files\\CMake\x08in\\cmake.exe', '-G Visual Studio 11 Win64', 'C:\\Users\\ochitaya\\Desktop\new\\myProj']' returned non-zero exit status 1
</code></pre>
| <p>A backslash (<code>\</code>) in a Python string is an escape character. That's why the string <code>"C:\Program Files\CMake\bin\cmake.exe"</code> is translated to <code>C:\\Program Files\\CMake\x08in\\cmake.exe</code> (notice that <code>\b</code> equals <code>\x08</code>). To fix this, tell Python you want the string to be read as-is, or in other words, as a <strong>raw</strong> string, by prefixing the string with <code>r</code>:</p>
<pre><code>cmakeCmd = [r"C:\Program Files\CMake\bin\cmake.exe",'-G Visual Studio 11 Win64', r'C:\Users\MyUser\Desktop\new\myProject']
</code></pre>
<p>For more on this topic, take a look at the official documentation on <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">string literals</a>.</p>
|
Oracle Apex apex_application.g_f10.COUNT is 0 <p>Oracle Apex: 5</p>
<p>This appears to be simple however I'm unable to get through this.</p>
<p>I'm testing the <code>apex_application.g_f10.COUNT</code> by inserting the checked value in a dummy table following is the code I'm using:</p>
<pre><code>declare
begin
:P20_LIST:=APEX_APPLICATION.G_F10.COUNT;
FOR i in 1 .. apex_application.g_f10.COUNT
LOOP
insert into test values (apex_application.g_f10(i) );
insert into test values (2045);
commit;
end loop;
end;
</code></pre>
<p>The process is not entering the loop even though values are checked on the following IR and <code>:P20_LIST</code> is 0:</p>
<pre><code> select INVENTORY_ITEM_ID,
apex_item.checkbox(10,INVENTORY_ITEM_ID) selected,
NAME,QUANTITY,SERIAL_NUMBER,IIL_NAME from inventory_items@NAM;
</code></pre>
<p>Please advise.</p>
<p>Thanks</p>
| <p>When ever we use check box as report column in report we have to make sure that column attribute should be <strong><em>Standard report column</em></strong> .Then only it will written the value </p>
<p><a href="https://i.stack.imgur.com/flYag.png" rel="nofollow"><img src="https://i.stack.imgur.com/flYag.png" alt="enter image description here"></a></p>
|
How to insert values to a database in Class B from a JTextField input that is in Class A <p>I am making a Online food ordering system for a project but i m still new to java. I have two classes. Signin.java and other is mextable.java. I am trying to access a textfield (part of signin.java), read <em>that</em> value from Mextable.java and insert that value into a table inside MexTable.java. </p>
<p>I am able to read the value from the <code>JTextField</code> in signin.java. I am also able to take that data and insert it to a table <code>login</code> in the same class, signin.java. </p>
<p>So my question is exactly <strong>how do I do the same in a different class? Means read and insert the username (that was entered in<code>JTextField</code> in signin.java) into table <code>orders</code>(which is part of the Mextable.java)?</strong> </p>
<p><img src="https://i.stack.imgur.com/4kfDq.png" alt="Signin.java Login page Screenshot"></p>
<p><img src="https://i.stack.imgur.com/KoXHq.png" alt="ORder Table from MExTable.java"></p>
<p><strong>Signin.java code</strong>(i have added just the main lines of the code):</p>
<pre><code> public class signin extends javax.swing.JFrame {
Connection conn;
OracleResultSet rs = null;
OraclePreparedStatement pst;
public signin() {
initComponents();
connect();
}
public void connect()
{
// connection with database
}
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
protected static javax.swing.JTexfield userTF;
try{
String pass = passTF.getText().trim();
String user = userTF.getText().trim();
String sql = "select uname,pass"
+ " from login "
+ "where uname = '"+user+"' "
+ "AND pass = '"+pass+"'";
pst = (OraclePreparedStatement) conn.prepareStatement(sql);
rs = (OracleResultSet) pst.executeQuery(sql);
// remaining code
}
//catch block
}
</code></pre>
<p><strong>Mextable.java:</strong></p>
<p>accessing the component value of the userTF textfield from the Signin.java is apparently not working because that value is not being inserted. Instead of that value, NULL is inserted. Rest of the values in this insert query are inserted in the table <code>orders</code>. </p>
<pre><code> private void ConOrd2ActionPerformed(java.awt.event.ActionEvent evt) {
try{
signin l = new signin();
l.getComponent(0).getName();
int rows = jTable23.getRowCount();
String user4 = l.userTF.getText().trim();
String sqli = "insert into orders"
+ "(o_id,item_id, order_name, uname)"
+ " values (ord_seq.nextval,?,?,'"+user4+"')";
//o_id,item_id,order_name is inserted and uname value is added as
//Null instead of the username value in the JTextfield in the Signin page.
pst = (OraclePreparedStatement) conn.prepareStatement(sqli);
for(int row =0; row < rows; row++)
{
String item2= (String)jTable23.getValueAt(row, 0);
String fooname2= (String)jTable23.getValueAt(row, 1);
pst.setString(1, item2);
pst.setString(2, fooname2);
pst.execute();
}
pst.executeUpdate();
conn.commit();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
</code></pre>
| <p>As far as i can analys from the question the flow goes from signin to mextable. And everyuser will have the username.in that case you can make the field JTextField as public static and use that field in the mextable class. </p>
<p>In signin class</p>
<p>Public static JTextField val ;</p>
<p>And to access in mextable use</p>
<p>Class name.variablename;</p>
<p>Signin.val;</p>
|
More Elegant Way of Coding a Setter <p>I was wondering if their was a smarter and more elegant way of writing a setter, or for that matter, any code which has to check for whether user input is correct</p>
<p>This just seems odd. I'm a novice, so maybe this is just the standard way of approaching this problem, but if not, I'd appreciate knowing what the 'smart' way is</p>
<pre><code>public void setMonth(){
boolean run = true;
while(run){
int input = scan.nextInt();
if(input > 0 && input < 13){
this.month = input;
run = false;
}
}
}
</code></pre>
| <p>First of all you can simplify your code like this:</p>
<pre><code> public void setMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)
this.month = input;
}
</code></pre>
<p>In addition to that I'd separate this into two functions. A setter should only set a value.</p>
<pre><code> public void setMonth(int month) {
if(month > 0 && month <= 12) {
this.month = month;
} else {
throw new IllegalArgumentException("Month has to be a value between 1 and 12 inclusively. Actual value was :" + month);
}
}
public void readMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)
setMonth(input);
}
</code></pre>
<p>As suggested by ChiefTwoPencils, you can furthermore extract the setter into an additional class. Thus separating user input and data even more.</p>
<pre><code> class MonthDataHolder {
private int month;
public MonthDataHolder(int month) {
setMonth(month);
}
public void setMonth(int month) {
if(isValidMonthValue(month)) {
this.month = month;
} else {
throw new IllegalArgumentException("Month has to be a value between 1 and 12 inclusively. Actual value was :" + month);
}
}
private boolean isValidMonthValue(month) {
return month >= 1 || month <= 12;
}
}
class InputReader {
public MonthDataHolder readMonth() {
int input = 0;
do {
input = scan.nextInt();
} while(input <= 0 || input >= 13)
return new MonthDataHolder(input);
}
}
</code></pre>
|
Trying to Solve Numerical Diff Eq Using Euler's Method, Invalid Value Error <p>I am trying to learn it from this website: <a href="http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb" rel="nofollow">http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb</a></p>
<p>I was trying to code it with as little help as possible, but I kept getting this error:</p>
<p>C:\Users\"My Real Name"\Anaconda2\lib\site-packages\ipykernel__main__.py:29: RuntimeWarning: invalid value encountered in double_scalars</p>
<p>With no data points on my plot. So I literally pasted all the code in directly from the website and I still get there error! I give up, can someone help a python newbie?</p>
<pre><code>import numpy as np
from matplotlib import pyplot
from math import sin, cos, log, ceil
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
# model parameters:
g = 9.8 # gravity in m s^{-2}
v_t = 30.0 # trim velocity in m s^{-1}
C_D = 1/40 # drag coefficient --- or D/L if C_L=1
C_L = 1 # for convenience, use C_L = 1
### set initial conditions ###
v0 = v_t # start at the trim velocity (or add a delta)
theta0 = 0 # initial angle of trajectory
x0 = 0 # horizotal position is arbitrary
y0 = 1000 # initial altitude
def f(u):
v = u[0]
theta = u[1]
x = u[2]
y = u[3]
return np.array([-g*sin(theta) - C_D/C_L*g/v_t**2*v**2, -g*cos(theta)/v + g/v_t**2*v, v*cos(theta), v*sin(theta)])
def euler_step(u, f, dt):
u + dt * f(u)
T = 100 # final time
dt = 0.1 # time increment
N = int(T/dt) + 1 # number of time-steps
t = np.linspace(0, T, N) # time discretization
# initialize the array containing the solution for each time-step
u = np.empty((N, 4))
u[0] = np.array([v0, theta0, x0, y0])# fill 1st element with initial values
# time loop - Euler method
for n in range(N-1):
u[n+1] = euler_step(u[n], f, dt)
x = u[:,2]
y = u[:,3]
pyplot.figure(figsize=(8,6))
pyplot.grid(True)
pyplot.xlabel(r'x', fontsize=18)
pyplot.ylabel(r'y', fontsize=18)
pyplot.title('Glider trajectory, flight time = %.2f' % T, fontsize=18)
pyplot.plot(x,y, 'k-', lw=2);
</code></pre>
| <p>The solution is very simple. You forgot the return statement in euler_step.
Change</p>
<pre><code>def euler_step(u, f, dt):
u + dt * f(u)
</code></pre>
<p>to</p>
<pre><code>def euler_step(u, f, dt):
return u + dt * f(u)
</code></pre>
<p>and it will work</p>
|
How to structure big projects in Angular2? <p>We are looking into Angular2 right now and want to introduce it into the next project.
There are two things that are bugging us right now. </p>
<ol>
<li>How big should an Angular2 application maximal get? </li>
<li>How should we structure a >3MM project?</li>
</ol>
<p>We did research on both topics, but didnt find any good advices or best practices. Are there any good guidelines on that topic?</p>
<p>Regards
Alexander</p>
| <blockquote>
<p>Are there any good guidelines on that topic?</p>
</blockquote>
<p>For best practices, checkout <a href="https://angular.io/styleguide" rel="nofollow">the official style guide</a></p>
<blockquote>
<p>How big should an Angular2 application maximal get? </p>
</blockquote>
<p>I'm not aware of a size limit. The framework was design with scalability in mind. For large projects, you'll want to load only the components you need at startup, and use lazy loading to download and setup the other modules <a href="https://angular.io/docs/ts/latest/guide/router.html#!#asynchronous-routing" rel="nofollow">only if the user requests them</a>. </p>
<blockquote>
<p>How should we structure a >3MM project?</p>
</blockquote>
<p>You have at least two great options to see how the project should be structured</p>
<ul>
<li><p>Use <a href="https://github.com/angular/angular-cli/blob/master/README.md" rel="nofollow">the <code>Angular CLI</code></a> to create your project and add its modules and components. This will automatically structure everything for you</p></li>
<li><p>Study one of the several community-built project templates that try to stick to best practices. You can go through the file structure and look for yourself. <a href="https://github.com/mgechev/angular-seed/blob/master/README.md" rel="nofollow"><code>Angular2-seed</code></a> could be a good starting point because it's also well documented.</p></li>
</ul>
|
How to connect X-Lite softphone from host to guest vm with asterisk? <p>I am desperate. I've install asterisk on vm 1 (centos) and opensips on vm2(centos), and everything works well so far. Now I need to connect softphone from host to vm1 (to make a call (I'm traying to set up auto-dial out system))) and don't know how to. I use host-only networking between vm's </p>
<p>vm1 - 192.168.56.3
vm2 - 192.168.56.4
host - I've set up rule in firewall, to make traffic enabled between vm's and host, but can't ping from guest to host/ host to guest.</p>
| <p>Simplest way - use bridged network to your router.</p>
<p>But host-only also work ok(at least in vmware and virtualbox), check your firewall rules</p>
|
PHP session_start doesn't work <p>My issue is that, when I use session_start(); in my php code, instead of a PHPSESSID cookie being set, a cookie with blank title and value "HttpOnly" is set instead. Using var_dump($_SESSION), I see that I can set session variables and they'll display on the page, but they won't display on any other page. For what it's worth, the two pages are at: login.domain.com/index.php and login.domain.com/login. The same code works fine locally, and other php files running on different subdomains on the same server work. I can't find any info, so if anyone has any ideas, I'd love to hear them.</p>
<p>This is the php on index.php:</p>
<pre><code> <?php
session_start();
?>
</code></pre>
<p>And this is the php on login/login.php</p>
<pre><code><?php
session_start();
$role = 0; //default to "guest"
$was_success = false; //default to a failed login
if(isset($_POST["user"]) && isset($_POST["password"])){ //if the post details are set then continue
$pass = password_hash("PASSWORD", PASSWORD_DEFAULT);
if (!isset($_COOKIE["mellifluous_loginRefer"])){
$arr = array("Username" => $_POST["user"],
"Error" => "No destination set!",
"Success" => false
);
die(json_encode($arr));
}
if (password_verify($_POST["password"], $pass) && ($_POST["user"] == "USER")){
$was_success = true;
if ($_COOKIE['mellifluous_loginRefer'] == "home"){
$_SESSION['mellifluous']['home']['username'] = $_POST['user'];
}
}
else $was_success = false;
$arr = array("Username" => $_POST["user"],
"Role" => $role,
"Success" => $was_success
);
if ($was_success) setcookie("mellifluous_loginRefer", "", time() - 10, "/");
echo(json_encode($arr));
//echo "You sent in: ";//Username: " . $_POST["user"] . " Password: ";//. $password;
}
else if(isset($_GET["user"]) && isset($_GET["password"])){
die("This interface has been deprecated.");
//$pass = password_hash($_POST["password"], PASSWORD_DEFAULT);
$arr = array("Username" => $_GET["user"]);
echo(json_encode($arr));
//echo "You sent in: ";//Username: " . $_POST["user"] . " Password: ";//. $password;
}
else{
die("ERROR!");
}
?>
</code></pre>
<p>Many thanks in advance!</p>
| <p>Check assigned values to <code>session.use_cookies</code>, <code>session.use_only_cookies</code> on php.ini file in your server. </p>
<p>You need to set the value of <code>session.use_cookies</code> and <code>session.use_only_cookies</code> in php.ini:</p>
<pre><code>session.use_cookies=1
session.use_only_cookies=0
</code></pre>
|
How do you define a function during dynamic Python type creation <p>(This is in Python 3 btw)</p>
<p>Okay so say we use <code>type()</code> as a class constructor:</p>
<p><code>X = type('X', (), {})</code></p>
<p>What I'm trying to find is how would <code>type()</code> accept a function as an argument and allow it to be callable? </p>
<p>I'm looking for an example of how this could be accomplished. Something along the lines of:</p>
<pre><code>>>> X = type('X', (), {'name':'World', 'greet':print("Hello {0}!".format(name))}
>>> X.greet()
Hello World!
</code></pre>
| <p>You need to pass the function. In your code, you call the function, and pass the result.</p>
<p>Try:</p>
<pre><code>def print_hello(self):
print("Hello {0}!".format(self.name))
X = type('X', (), {'name':'World', 'greet': print_hello})
</code></pre>
|
How to convert UTC timezone to local timezone location <p>I have following Code:</p>
<pre><code>UTC<br/>
<div id="divUTC">'UTC+5:30'</div><br/>
<br/>
<div id="divLocal">
</div>
</code></pre>
<p>In My javascript I am trying to convert UTC+5:30 to IST-Indian Standard Time (Chennai, Kolkata, Mumbai, New Delhi)
UTC value could be anything so does the converted value.</p>
<pre><code>var divUtc = $('#divUTC');
var divLocal = $('#divLocal');
//get text from divUTC and convert to local timezone
</code></pre>
<p>I know i have not placed any code here, But sorry its not hitting my mind, I have option of putting key-value pairs but that's not effective. Please suggest.</p>
| <p>One of the problems of converting UTC+XX to whatever local timezone text is that it is not 1:1 mapping. Still, if you use momentjs with time zones, you could get yourself a list of possible locations.</p>
<p>1) get all the known timezones:</p>
<pre><code>var names = moment.tz.names();
// names now contain an array of tz names
</code></pre>
<p>2) iterate over names array, create moment object in particular timezone and get its offset. Following code will print the offssets for each tz name for this moment.</p>
<pre><code>for( var i = 0; i < names.length; i++){
console.log(moment.tz(names[i]).format('Z'));
}
</code></pre>
<p>3) within that loop you may compare the utcOffset of the moment or textual representation of the offset and get a set of timezones that fit your offset.</p>
<p>Here is a loop that will print all the tz names for +05:30.</p>
<pre><code>var names = moment.tz.names();
for( var i = 0; i < names.length; i++){
if(moment.tz(names[i]).format('Z') === "+05:30"){
console.log(names[i])
}
}
// output:
// Asia/Calcutta
// Asia/Colombo
// Asia/Kolkata
</code></pre>
<p>Also, keep in mind that many regions have DST time changes, meaning that region may have a different offset depending on the time of the year.</p>
|
Python - First and last character in string must be alpha numeric, else delete <p>I am wondering how I can implement a string check, where I want to make sure that the first (&last) character of the string is alphanumeric. I am aware of the <code>isalnum</code>, but how do I use this to implement this check/substitution?</p>
<p>So, I have a string like so:</p>
<pre><code>st="-jkkujkl-ghjkjhkj*"
</code></pre>
<p>and I would want back:</p>
<pre><code>st="jkkujkl-ghjkjhkj"
</code></pre>
<p>Thanks..</p>
| <p>Though not exactly what you want, but using str.strip should serve your purpose</p>
<pre><code>import string
st.strip(string.punctuation)
Out[174]: 'jkkujkl-ghjkjhkj'
</code></pre>
|
Cocoa protocol for cut, copy and paste actions <p>Is there any protocol in Cocoa implementing standard actions for cut: copy paste:, like there is UIResponderStandardEditActions for UIKit?</p>
<p>I would like to do something like this without implementing delete(_:) in this class, with the new Swift3 #selector:</p>
<pre><code>override func supplementalTarget(forAction action: Selector, sender: Any?) -> Any? {
switch action{
case #selector(delete(_:)):
return outlineView.delegate
default:
return nextResponder
}
}
</code></pre>
<p>Thanks</p>
| <p>You can define your own protocol:</p>
<pre><code>@objc protocol MyStandardActionProtocol {
func cut(_: Any)
func copy(_: Any)
func paste(_: Any)
}
</code></pre>
<p>And use <code>#selector</code> like:</p>
<pre><code>override func supplementalTarget(forAction action: Selector, sender: Any?) -> Any? {
switch action{
case #selector(MyStandardActionProtocol.cut(_:)):
return ...
//...
default:
return nextResponder
}
}
</code></pre>
<p>Type information is not included in <code>Selector</code> instances, so this will work even if no classes conform to the protocol.</p>
|
Method that returns the first n odd numbers <p>Just a quick question -- I'm probably overlooking something here. </p>
<p>The below method outputs the first 2 odd numbers correctly: [1,3]</p>
<p>If I'm not mistaken, shouldn't I want the length of the array to eventually <strong>equal</strong> n? As I understand it, the length of the outputted array [1,3] is 2, which also represent the first n-many odds: 2.</p>
<p>As such, the comparison in line 6 would now be <strong><=</strong> rather than <strong><</strong></p>
<p>However, if I do that, first_n_odds(2) would now equal [1,3,5], which gives me the first <em>three</em> odds. What's going on here?</p>
<p>Thanks!</p>
<pre><code>def first_n_odds(n)
array = []
current_number = 0
while array.length < n
if current_number % 2 == 1
array << current_number
end
current_number += 1
end
return array
end
puts first_n_odds(2) # output is [1,3]
</code></pre>
| <p>Let's do your example with <code>n == 2</code>.</p>
<p>Iteration 1: <code>array.length == 0</code>.
Iteration 2: <code>array.length == 1</code>.</p>
<p>Both of these values are <code>< 2</code>. Now if you change <code><</code> to <code><=</code>, you'd have a 3rd iteration where <code>array.length == 2</code> since your check happens <em>before</em> adding the new element to the array.</p>
<p>Since you seem to be fairly new to Ruby, here are some ways to define the method in a more idiomatic way:</p>
<pre><code># Mapping over a range
def first_n_odds_1(n)
(0...n).map { |x| x * 2 + 1 }
end
# Mapping over an Enumerator
def first_n_odds_2(n)
n.times.map { |x| x * 2 + 1}
end
# Using Numeric#step + Enumerable#take
def first_n_odds_3(n)
1.step(Float::INFINITY, 2).take(n)
end
# A more explicit version of the previous method
def first_n_oods_4(n)
1.step(by: 2, to: Float::INFINITY).take(n)
end
</code></pre>
|
Remove the function and command from the output <p>I have trying out defaultdict with lamba function. However, I could not get the output I want. I will demonstrate with more details. Below is my code:</p>
<pre><code>from collections import defaultdict
the_list = [
('Samsung', 'Handphone', 10),
('Samsung', 'Handphone', -1),
('Samsung', 'Tablet', 10),
('Sony', 'Handphone', 100)
]
d = defaultdict(lambda: defaultdict(int))
for brand, thing, quantity in the_list:
d[brand][thing] += quantity
</code></pre>
<p>My result is:</p>
<pre><code>defaultdict(<function <lambda> at 0x02715C70>, {'Sony': defaultdict(<type
'int'>, {'Handphone': 100}), 'Samsung': defaultdict(<type 'int'>, {'Handphone':
9, 'Tablet': 10})})
</code></pre>
<p>I want my result to be this:</p>
<pre><code>{
'Samsung': {
'Handphone': 9,
'Tablet': 10
},
'Sony': {
'Handphone': 100
}
}
</code></pre>
<p>How am I supposed to do remove the <code>defaultdict(<function <lambda> at 0x02715C70>, {'Sony': defaultdict(<type int'>,</code> to achieve my desired output. Thank you!</p>
| <p>Just convert each <code>defaultdict</code> back to a regular <code>dict</code>, you can do it easily using <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/738/dictionary-comprehensions#t=201610160749050862097">dict comprehension</a>:</p>
<pre><code>{ k:dict(v) for k,v in d.items() }
#output
{'Sony': {'Handphone': 100}, 'Samsung': {'Tablet': 10, 'Handphone': 9}}
</code></pre>
|
Filter search data from Microsoft Access Database and filter in datagridview c# <p>I use this code to try and make the application filter the text in the textbox but it refuses to do so and an error message keeps popping up. Here is the code:</p>
<pre><code>using System.Windows.Forms;
using System.Configuration;
using System.Data.OleDb;
namespace TestBarcode
{
public partial class StaffHome : Form
{
private OleDbConnection connection = new OleDbConnection();
public StaffHome()
{
InitializeComponent();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Projects\POS\Database\MainDatabase_POS.accdb;Persist Security Info=False;";
}
private void StaffHome_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from InventoryManagement";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
try
{
connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand("Select * from InventoryManagement where ID like '" + textBox1.Text + "%'", connection);
OleDbDataAdapter adp = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show("Error" + ex);
}
</code></pre>
<p>Is there a way to make this happen? If so, please help. Thanks.</p>
<p>EDIT: Here is an image of the error msg.
<a href="https://i.stack.imgur.com/JTi59.png" rel="nofollow">Error msg Box</a></p>
| <p>The second command calls NEW on the OleDbConnection variable. The result is that this recreates the OleDbConnection but misses the initialization of the required connectionstring </p>
<p>In this context you should still use the global object and do not create a new connection.
So just remove this line</p>
<pre><code> // This creates a new OleDbConnection without the connection string
connection = new OleDbConnection();
</code></pre>
<p>However I dislike a lot using a global object for a connection. The connection internally uses unmanaged resources that can be difficult to handle correctly in case of exceptions and it is always preferable to create a local connection and keep global only the connection string. This pattern allows the introduction of the using statement that destroys correctly the connection and frees the unmanaged resources kept by the connection</p>
|
How get to img element <p>I want when user clicked on <code>.fa-search-plus</code> an alert shows the src of the <code>.img-reponsive</code></p>
<p>Here is my code:</p>
<pre><code><div class="col-lg-push-4 col-lg-3 col-md-3 col-sm-12 col-xs-12">
<div class="grid">
<figure class="effect-hera">
<img class="img-responsive second"src="images/book4.png" data- toggle="modal" data-target="#myModal">
<figcaption>
<p>
<a href="imageideas.org/pdf/4.pdf"><i class="fa fa-download"></i></a>
<a data-toggle="modal" data-target="#myModal"><i class="fa fa-search-plus"></i></a>
</p>
</figcaption>
</figure>
</div>
</div>
<script>
$(".fa-search-plus").click(function(){
alert ($(this).parent().parent().find('.img-responsive').attr('src'));
})
</script>
</code></pre>
| <p>Using this code may be helpful for you:</p>
<pre><code>var someimage = document.getElementById('this_one');
var myimg = someimage.getElementsByTagName('img')[0];
var mysrc = myimg.src;
</code></pre>
|
PCI Express interrupts in driver <p>Hello iam developing PCIe communication between Xilinx FPGA and Intel PC...
I have written a kernel module(linux driver), i am using INTx interrupts.
I am facing the problem in interrupt handling....</p>
<p><strong>Before loading kernel module:</strong></p>
<p>from lspci: INT A-->11</p>
<p>from config read : INT A-->11</p>
<p>from /proc/interrupts : Nothing because irq not registerd</p>
<p><strong>After loading kernel module:</strong></p>
<p>from lspci: INT A-->16</p>
<p>from config read : INT A-->11</p>
<p>from /proc/interrupts : INT 11 registerd</p>
<p>When i run the program in FPGA it was sending interrupt to IRQ-16 and saying no body cared and it was disabled.</p>
<p><em>in my module_init:</em></p>
<pre><code>request_irq(dev->gIrq, XPCIe_IRQHandler, IRQF_SHARED, gDrvrName, gDev));
</code></pre>
<p><em>My irq handler:</em></p>
<pre><code>static irqreturn_t XPCIe_IRQHandler(int irq, void *dev_id, struct pt_regs *regs)
{ return IRQ_HANDLED; }
</code></pre>
<p>So anybody can say what the problem may be....</p>
| <p>You don't show where your <code>dev->gIrq</code> is set from, but your kernel module should be taking the interrupt number from the <code>struct pci_dev</code> associated with your device. See this comment in <code>include/linux/pci.h</code>:</p>
<pre><code>struct pci_dev {
...
/*
* Instead of touching interrupt line and base address registers
* directly, use the values stored here. They might be different!
*/
unsigned int irq;
</code></pre>
|
How to write Node.js binary stream from zip to an S3 <p>I want to zip up files and dump the binary output right to AWS S3. I'm testing out my code first by making sure it can even write to a local ZIP file, which is not working.</p>
<pre><code>function zipFiles(filenames) {
return new Promise((resolve, reject) => {
const child = spawn(zipCmd, ['-'].concat(filenames));
let buffer = '';
child.stdout.on('data', (data) => {
buffer += data.toString();
});
child.stderr.on('data', (data) => {
// console.error(data.toString());
});
child.on('close', (code) => {
fs.writeFileSync('testing.zip', buffer);
resolve(code);
});
});
}
</code></pre>
<p>This results in a mangled zip file. I'm not really sure how to handle the buffer stream from <code>spawn</code> and assemble it into something that will work with <code>s3.putObject</code> and <code>fs.writeFileSync</code> (as a method of testing).</p>
| <p>Got it!</p>
<pre><code>function zipFiles(filenames) {
return new Promise((resolve, reject) => {
const out = fs.openSync('testing.zip', 'a');
const child = spawn(zipCmd, ['-'].concat(filenames));
let buffer = new Buffer('');
child.stdout.on('data', (data) => {
buffer = Buffer.concat([buffer, data]);
});
child.stderr.on('data', (data) => {
// console.error(data.toString());
});
child.on('close', (code) => {
fs.writeFileSync('testing.zip', buffer);
resolve(code);
});
});
}
</code></pre>
|
How to map json arrays in angularjs controller <p>I am having problem in mapping json array in angularjs, can someone please look how can i correctly map the arrays and iterate their values. In arrays icdCode requires to be dynamic field (this is the other part i need help on) how can i achieve this correctly. thanks</p>
<p><b>Way i am mapping in Controller</b></p>
<pre><code> $scope.preAuthorizationInfo.collections.preAuthClinicalDetailInfoFormVO.active = active;
</code></pre>
<p><b>Json arrays</b></p>
<pre><code> "preAuthDiagnosisVOs": [
{
"preauthDiagnosisId": 165,
"diagnosisVO": {
"diagnosisId": 171,
"diagnosisCode": "Provisional",
"icdCode": {
"icdCodeId": 1,
"description": "Other intestinal Escherichia coli infections",
"icdCode": "Other intestinal Escherichia coli infections",
"icdCodeChapter": "Certain infectious and parasitic diseases",
"icdCodeCode": "A04.4"
},
"active": false
},
"active": true
},
{
"preauthDiagnosisId": 166,
"diagnosisVO": {
"diagnosisId": 172,
"diagnosisCode": "differential",
"icdCode": {
"icdCodeId": 2,
"description": "Other viral enteritis",
"icdCode": "Other viral enteritis",
"icdCodeChapter": "Certain infectious and parasitic diseases",
"icdCodeCode": "A08.3"
},
"active": false
},
"active": true
}
]
},
</code></pre>
| <p>If You want to iterate over this object , You can use nested loop</p>
<pre><code>angular.forEach(your_object.preAuthDiagnosisVOs, function(value, key) {
if (angular.isObject(value)) {
angular.forEach(value, function(value1, key) {
if (angular.isObject(value1)) {
angular.forEach(value1, function(value2, key) {
if (angular.isObject(value2)) {
angular.forEach(value2, function(value3, key) {
console.log(key + " : " + value3);
});
} else {
console.log(key + " : " + value2);
}
});
} else {
console.log(key + " : " + value1);
}
});
} else {
console.log(key + " : " + value);
}
});
</code></pre>
<p>And if you want just that active value just use </p>
<p><code>yourObject.preAuthDiagnosisVOs[0].active</code> or <code>yourObject.preAuthDiagnosisVOs[1].active</code></p>
<p>Hope this helps you . Thanks</p>
|
logstash parsing IPV6 address <p><strong>I am a newbie to logstash / grok patterns.</strong></p>
<p>In my logfile i have a line in this format as below:</p>
<pre><code>::ffff:172.19.7.180 - - [10/Oct/2016:06:40:26 +0000] 1 "GET /authenticator/users HTTP/1.1" 200 7369
</code></pre>
<p>When I try to use a simple IP pattern matching %{IP}, using grok constructor, it shows only partial match:</p>
<pre><code>after match: .19.7.180 - - [10/Oct/2016:06:33:58 +0000] 1 "POST /authenticator/searchUsers HTTP/1.1" 200 280
</code></pre>
<p>So, only a part of the ip address matched, as the portion 'after match' still shows remaining portion of ip address.</p>
<p>Queries:
1. What is this format of IP address ::ffff:172.19.7.180?
2. How to resolve this issue, to ensure IP address is correctly parsed?</p>
<p><strong>BTW, I am using nodejs middleware morgan logger, which is printing IP address in this format.</strong></p>
| <p>Note that the log contains <strong>both</strong> IPv4 and IPv6 addresses separated by a colon, so the correct pattern you need to use is the following one:</p>
<pre><code>%{IPV6:ipv6}:%{IPV4:ipv4}
</code></pre>
<p>Then in your event you'll have two fields:</p>
<pre><code>"ipv6" => "::ffff"
"ipv4" => "172.19.7.180"
</code></pre>
<p>This will work until <a href="https://github.com/logstash-plugins/logstash-patterns-core/issues/161" rel="nofollow">this issue</a> is resolved.</p>
|
With Chromium Embedded is there a way to communicate to the program, from Javascript? <p>If you have a chromium embedded web browser widget in an application, is there a way to notify the application that something has occurred at any point in time? for example let's say an item is resized or a button is clicked and it is a javascript based page loaded in the chromium embedded widget. How do you notify the C++ or Delphi application (or any application) via code and send a message or callback to it? I am looking for something like a sendMessage feature, to communicate back to the application that something has occurred.</p>
<p>Examples of how to do this can be in C++, .Net, or Delphi, or any language... as I could simply port the code over to my Delphi language.</p>
<p>In other words, how do you communicate from javascript, to the application that has the chromium embedded web browser in it? When the page is done loading, you can communicate through that page load end event that occurs... however javascript code tends to run even after the page is loading, especially if the user uses a mouse to drag an item on the page or click a button.. So how do you communicate back to the C++/Delphi application any time you want, that something has happened? </p>
<p>FYI full access to the html/java code is available, i.e. I can add my own code in the javascript.. any code I want. So if there is something like sendMessageBackToApp then I would like to add it.</p>
<p>If this feature is not available, it certainly would be useful. Communication between the application and the javascipt/html is essential for the application to be truly powerful. </p>
| <p>The following addition to the Chromium GuiClient demo works for me in D7:</p>
<pre><code>procedure TMainForm.TestJS;
begin
if crm.Browser <> nil then
crm.Browser.MainFrame.ExecuteJavaScript(
'alert(''JavaScript execute works!''); console.log(''From Javascript'')', 'about:blank', 0);
end;
procedure TMainForm.crmConsoleMessage(Sender: TObject; const browser:
ICefBrowser; const message, source: ustring; line: Integer; out Result:
Boolean);
begin
ShowMessage('OnConsoleMessage: ' + Message);
Result := True;
end;
</code></pre>
<p>See here for a fuller discussion: <a href="https://groups.google.com/forum/#!topic/delphichromiumembedded/uDxAUTvXqzc" rel="nofollow">https://groups.google.com/forum/#!topic/delphichromiumembedded/uDxAUTvXqzc</a></p>
|
can someone help me to fix this error <pre><code> UIAlertController *alert = [[UIAlertController alloc] initWithTitle: alertString message:nil
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
</code></pre>
<p>I'm having this error: </p>
<pre><code>No visible @interface for 'UIAlertController' declares the selector 'show'
</code></pre>
<p>and this : <code>No visible @interface for 'UIAlertController' declares the selector 'initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:'</code></p>
| <p>This true of step to declare <code>UIAlertController</code> </p>
<pre><code>UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
// add action button
UIAlertAction *okAction = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:okAction]; // add action button to alert controller
// present alert controller in view
[self presentViewController:alertController animated:YES completion:nil];
</code></pre>
|
Add data in recyclerview <p>In this way I create my <code>recyclerview</code> contents:</p>
<pre><code>MyAdapter adapter = new MyAdapter(new String[]{"one", "two", ..."});
rv.setAdapter(adapter);
</code></pre>
<p>But now I want add more data, for example, how can I add a new string <code>new String[]{"nine", "ten", ..."}</code> inside this <code>recyclerview</code>?</p>
<p>I need to add more data in this way. I also tried to see other discussion on stackoverflow, but nothing.</p>
<p>Edit:</p>
<pre><code>private List<list> list;
rv=(RecyclerView)findViewById(R.id.rv);
llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
list.add(new New("1", "a"));
list.add(new New("2", "b"));
RVAdapter adapter = new RVAdapter(Array);
rv.setAdapter(adapter);
rv.addOnScrollListener(new RecyclerView.OnScrollListener()
{
....
if ( visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
list.add(new New("9", "A"));
list.add(new New("10", "B"));
//method 1, but don't work:
RVAdapter adapter = new RVAdapter(list);
adapter.notifyDataSetChanged();
//method 2, this method work but don't add nothing, the rv is recrated with new list. the user is forced to go on top in this way.
RVAdapter adapter = new RVAdapter(list);
rv.setAdapter(adapter);
//method 3, return "cannot resolve method notifyDataSetChanged()"
RVAdapter adapter = new RVAdapter(list);
rv.notifyDataSetChanged();
}
</code></pre>
<p>Maybe the solution is similar at method 2, but why i see the error: "Cannot resolve..."?</p>
| <p>Take an ArrayList<>(), say stringList and add data to it. And then notify your adapter about dataset change.</p>
<p>Initialize your adapter with this data structure.</p>
<pre><code>MyAdapter adapter = new MyAdapter(stringList);
rv.setAdapter(adapter);
</code></pre>
<p>Add more items with this call.</p>
<pre><code>private void addItem(String item) {
stringList.add(item);
adapter.notifyDataSetChanged();
}
</code></pre>
|
SAP NetWeaver Application Server ABAP 7.03 trial, error during installation <p>Any suggestion as how to solve this installation error?</p>
<p><a href="https://i.stack.imgur.com/rzOPa.png" rel="nofollow"><img src="https://i.stack.imgur.com/rzOPa.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/BB1yw.png" rel="nofollow"><img src="https://i.stack.imgur.com/BB1yw.png" alt="enter image description here"></a></p>
| <p>Problem eventually solved by copying of [c:\windows\system32\drivers\etc] folder to [c:\windows\SysWOW64\drivers].</p>
|
setinterval working very randomly <p>Hi,</p>
<p>I have this code:</p>
<pre><code>//<![CDATA[
$(window).load(function(){
setInterval(function(){
// toggle the class every 10 seconds
$('body').addClass('new');
setTimeout(function(){
// toggle back after 10 seconds
$('body').removeClass('new');
},10000)
},10000);
});//]]>
</code></pre>
<p>This code is supposed to add the class "new" to body 10 seconds later after the page first loads and then remove it after 10 seconds again to start all over going into an endless loop. But it wont work as expected. Sometimes it takes way longer than 10 seconds to add the class and it removes it too soon. Some other times it does it only once and then the loop ends just like that. </p>
<p>Whats wrong here? A more effective and reliable alternative will be also welcome.</p>
<p>Thank you.</p>
| <p>You've told the code adding the class to run every 10 seconds. Every 10 seconds, you also schedule a timer to remove the class 10 seconds later. So as of the 20th second, you have a race — will the first timer get there first, or will the second? In any case, it won't have the result you want.</p>
<p>Use a single timer that toggles:</p>
<pre><code>setInterval(function() {
$("body").toggleClass("new");
}, 10000);
</code></pre>
<p>As for it taking a long time to start, remember that the <code>window</code> <code>load</code> event doesn't occur until <strong>all</strong> resources have finished downloading, including all of your images and such. So the whole process may be starting quite a bit later than you expect.</p>
<p>Also note that browsers are increasingly "dialing back" timers in inactive tabs, so your timer may not be running, or may run infrequently, when the window it's in doesn't have focus.</p>
<hr>
<p>From your comment:</p>
<blockquote>
<p>But just as a bonus. What if I want to have the class to last 20 seconds but keep the interval in 10 seconds?</p>
</blockquote>
<p>That complicates things. You could have a flag that you toggle, and only toggle the class when the flag is in one state or the other. E.g., something like:</p>
<pre><code>(function() { // Scoping function so the flag isn't a global
var flag = true;
setInterval(function() {
if (flag) {
$("body").toggleClass("new");
}
flag = !flag;
}, 10000);
})();
</code></pre>
<p>That will add the class at 10 seconds, toggle the flag at 20, remove the class at 30, toggle the class at 40, then start the cycle again. Adjust as needed.</p>
|
Issues with retrieving data from Access database using criteria from JTextField objects <p>I have created user login window in java and i am getting some issues regarding retrieving saved data from ms access database.
Here is my code:</p>
<pre><code>package databaseretrievedata;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import javax.swing.*;
public class Databaseretrievedata {
Databaseretrievedata(){
JFrame edit=new JFrame();
edit.setBounds(300,200,550,120);
edit.setUndecorated(false);
edit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setBounds(0,0,600,400);
edit.add(p);
JTextField field=new JTextField(20);
field.setBounds(100,200,120,20);
p.add(field);
JTextField field1=new JTextField(20);
field1.setBounds(100,300,120,20);
p.add(field1);
JButton b=new JButton("Click Me");
b.setBounds(0,100,100,20);
p.add(b);
JRootPane pane=b.getRootPane();
pane.setDefaultButton(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try {
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
Statement st=conn.createStatement();
String sql="select Username,Password from simba where Username='"+field+"'and Password='"+field1+"'";
ResultSet rs=st.executeQuery(sql);
if(rs.next())
{
JFrame editframe=new JFrame();
editframe.setBounds(300,200,400,200);
editframe.setUndecorated(false);
editframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editframe.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null,"No record Found");
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
});
edit.setVisible(true);
}
public static void main(String[] args) {
Databaseretrievedata v=new Databaseretrievedata();
}
}
</code></pre>
<p>Here is the file in the database where i saved my data.<a href="https://i.stack.imgur.com/qqZNy.png" rel="nofollow"><img src="https://i.stack.imgur.com/qqZNy.png" alt="enter image description here"></a></p>
<p>I have created one text field for username and password field for getting password from the user inside JFrame and when i entered the same username and password which i saved in ms access database i got 'No record Found'although i have saved that data in the database and i want this,that when user enter username and password in the provided fields then a new JFrame opens up.
I am not pretty sure where i am doing mistake.</p>
| <p>Your <code>sql</code> is missing something, your statement:</p>
<pre><code>String sql="select Username,Password from simba where Username='"+field+"'and Password='"+field1+"'";
</code></pre>
<p>This won't be what you're actually expecting here. Since the <code>JTextField</code> does not provide a special <code>toString()</code> method for its text, so that's why you can't find any matching entry in your database.</p>
<p>You need to retrieve the entered username, respectively the password by calling the <code>getText()</code> method on the <code>JTextField</code>:</p>
<p><code>String sql = "select Username,Password from simba where Username='"+field.getText()+"'and Password='"+field1.getText()+"'";</code></p>
<p>In such cases it is helpful to also print your query to the console to spot mistakes instantly</p>
|
Is there a popular Linux/Unix format for binary diffs? <p>I'm going to be producing binary deltas of multi-gigabyte files.</p>
<p>Naively, I'm intending to use the following format:</p>
<pre><code>struct chunk {
uint64_t offset;
uint64_t length;
uint8_t data[];
};
struct delta {
uint8_t file_a_checksum[32]; // These are calculated while the
uint8_t file_b_checksum[32]; // gzipped chunks are being written
uint8_t chunks_checksum[32]; // at the 96 octet offset.
uint8_t gzipped_chunks[];
};
</code></pre>
<p>I only need to apply these deltas to the original <code>file_a</code> that was used to generate a delta.</p>
<p>Is there anything I'm missing here?</p>
<p>Is there an existing binary delta format which has the features I'm looking for, yet isn't too much more complex?</p>
| <p>For arbitrary binaries, of course it makes sense to use a general purpose tool:</p>
<ul>
<li>xdelta</li>
<li>bspatch</li>
<li>rdiff-backup (rsync)</li>
<li>git diff</li>
</ul>
<p>(Yes, <code>git diff</code> works on files that aren't under version control. <code>git diff --binary --no-index dir1/file.bin dir2/file.bin</code> )</p>
<p>I would usually recommend a generic tool before writing your own, even if there is a little overhead. While none of the tools in the above list produce binary diffs in a format quite as ubiquitous as the "unified diff" format, they are all "close to" standard tools.</p>
<p>There is one other fairly standardised format that might be relevant for you: the humble hexdump. The <code>xxd</code> tool dumps binaries into a fairly standard text format by default:</p>
<pre><code>0000050: 2020 2020 5858 4428 3129 0a0a 0a0a 4e08 XXD(1)....N.
</code></pre>
<p>That is, offset followed by a series of byte values. The exact format is flexible and configurable with command-line switches.</p>
<p>However, <code>xxd</code> can also be used in reverse mode to <em>write</em> those bytes instead of dumping them.</p>
<p>So if you have a file called <code>patch.hexdump</code>:</p>
<pre><code>00000aa: bbccdd
</code></pre>
<p>Then running <code>xxd -r patch.hexdump my.binary</code> will modify the file <code>my.binary</code> to modify three bytes at offset <code>0xaa</code>.</p>
<p>Finally, I should also mention that <code>dd</code> can seek into a binary file and read/write a given number of bytes, so I guess you could use "shell script with <code>dd</code> commands" as your patch format.</p>
|
Symfony and Bootstrap dateTimePicker : expected a string <p>I am trying to create a DateTimePickerType to easily add a Bootstrap dateTimePicker to a field, simply by using the type "date_time_picker" in the Form Builder.<br>
Unfortunately I am running into some problems. Specifically, Symfony is giving me this error :</p>
<blockquote>
<p>Symfony\Component\Validator\ConstraintViolation<br>
Object(Symfony\Component\Form\Form).children[startDate] = Object(DateTime) - 2016-10-16T10:45:00+0200<br>
Caused by:<br>
Symfony\Component\Form\Exception\TransformationFailedException<br>
Unable to reverse value for property path "startDate": Expected a string.
Caused by:<br>
Symfony\Component\Form\Exception\TransformationFailedException<br>
Expected a string.</p>
</blockquote>
<p>So apparently my form is sending a DateTime object to my Controller, who has trouble converting it to String. In the database, the field is of type datetime. </p>
<p>Here is my DateTimePickerType :</p>
<pre><code>class DateTimePickerType extends AbstractType
{
/**
* @return string
*/
public function getParent()
{
return 'datetime';
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'empty_data' => new \DateTime(),
'widget' => "single_text",
'attr' => array(
'class' => 'addInput col-xs-12 dateSize noPadding noOutline dateTimePicker',
),
'format' => 'YYYY-MM-DD HH:mm',
'date_format'=>"dd/MM/yyyy hh:mm",
'html5' => false,
)
);
}
/**
* @param FormView $view
* @param FormInterface $form
* @param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'empty_data' => $options['empty_data'],
'widget' => $options['widget'],
'format' => $options['date_format'],
));
}
/**
* @return string
*/
public function getName()
{
return 'date_time_picker';
}
}
</code></pre>
<p>I have tried many different options for the resolver. If I remove the "new \DateTime()" in "empty_data", my form now sends a <code>null</code> value, and I get a nice SQL error trying to insert null into the database.</p>
<p>Snippet of <em>form_template.html.twig</em> :</p>
<pre><code>{% block date_time_picker_widget %}
<div class='input-group date' id='date-time-picker-{{ id }}'>
<input type="text" class="form-control" />
<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
</div>
{% include 'VMSFormTypeBundle:Template:date_time_picker_script.html.twig' %} {# link to the direct js script to make it datetimepicker #}
{% endblock %}
</code></pre>
<p>In <em>date_time_picker_script.html.twig</em> :</p>
<pre><code>{% autoescape false %}
<script type="text/javascript">
$(function () {
$('#date-time-picker-{{ id }}').datetimepicker();
});
</script>
{% endautoescape %}
</code></pre>
<p>Snippet of my <em>Form Builder</em> :</p>
<pre><code>$builder
->add('startDate','date_time_picker')
</code></pre>
<p>Thanks in advance</p>
<p><strong>EDIT</strong> : Just noticed the datetime that is sent by the form ignores what I select, and instead sends the current datetime (current day, hour and minute). </p>
| <p>Apparently this is because there's a need to convert the time format between PHP and JS. I fixed the problem by using only a DateType (time wasn't that necessary).</p>
<p>This might be useful for those who still need a DateTime, tho I haven't tested it : <a href="https://github.com/stephanecollot/DatetimepickerBundle" rel="nofollow">https://github.com/stephanecollot/DatetimepickerBundle</a></p>
|
How to use Quartz.NET with ASP.NET Core Web Application? <p>In traditional <code>ASP.NET</code> application, we (re-)intialize the <code>Quartz.NET</code> scheduler in the <code>Application_Start</code> handler in <code>global.asax.cs</code>.
But I have no ideas where to write the code for scheduling jobs as there isn't <code>global.asax.cs</code> in <strong><code>ASP.NET</code> Core Web application</strong>.
Should I put the code in <code>Startup.cs</code>?</p>
| <p>You may use <code>ConfigureServices</code> or <code>Configure</code> methods.
Although <code>Configure</code> method is mainly used to configure the HTTP request pipeline, the benefit is that you directly can use <code>IHostingEnvironment</code> (and so get configuration settings) and <code>ILoggerFactory</code> interfaces. And using <code>ConfigureServices</code> method those dependencies may be accessed if you create corresponding properties in <code>Startup</code> class.</p>
<pre><code>// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
</code></pre>
|
how to use owl carousel sync with RTL direction <p>i want to use owl carousel sync with RTL direction but not working</p>
<p>i wrote following style to fixed this problem bug my sync owl carousel not working : </p>
<pre><code>.owl-carousel .owl-item{
float: right !important;
}
</code></pre>
<p>what to do now?</p>
| <p>Try rtl: true</p>
<pre><code>$('.owl-carousel').owlCarousel({
rtl:true,
loop:true,
margin:10,
nav:true,
responsive:{
0:{
items:1
},
600:{
items:3
},
1000:{
items:5
}
}
})
</code></pre>
|
What do I need to include SQL Server Express in my Wizard installation? <p>I've just finished a project with a SQL Serer database, so in my launch project I use this connection string </p>
<pre><code>Data Source=(local);Integrated Security=True
</code></pre>
<p>And I check every time if database exists locally; if not, I execute a script to create the database and tables ... it works 100% without any problems.</p>
<p>But now I want to publish my project in Advanced Installer.. but when I try to install it on another PC, there was a error that said that I can't query database cause server is missing ...</p>
<p>I need the minimum prerequisite to add it in wizard installation, I've tried SQL Server 2005 Express, but it is still not working, the same error ... </p>
<p>Help me please ...</p>
<p>NB : I'm working with SQL Server 2014</p>
| <p>You seem to have an <em>unnamed</em> default instance on your development PC so that you can connect to it using <code>data source=(local)</code>.</p>
<p>When SQL Server <strong>Express</strong> is installed, by default, it uses a <strong>named</strong> instance of <code>SQLEXPRESS</code>, so your connection string should have</p>
<pre><code>data source=(local)\SQLEXRPESS;....
</code></pre>
<p>in it, to connect to the <code>SQLEXPRESS</code> instance.</p>
<p>Or you need to change your SQL Server Express installation to install as the <em>default, unnamed instance</em>, too.</p>
|
how to synchronize mysql on 2 different workspaces? <p>I have 2 computer in 2 different workspace.<br>
I want work on 1 project in 2 place.<br>
I use bitbuket.org as vcs system for this project.<br>
I need synchronize database (mysql) for this 2 computer .<br>
What is best practice for this work? </p>
| <p>The best practice in this case, on dev environment, is to use db migrations (e.g. <a href="http://www.liquibase.org/" rel="nofollow">liquibase</a> or tool provided with framework you've chosen) and data fixtures (sample solution for <a href="http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html)" rel="nofollow">PHP and Doctrine</a>).</p>
|
Ruby on Rails : Find record of an object without querying database <p>I want to know how to get a specific record from an object example</p>
<pre><code>@user = User.all
</code></pre>
<p>In <code>index.html.erb</code>, I want to show only the record that in the 3rd order , I try, but this gives me all the records. : </p>
<pre><code><% @user.each do |u| %>
</code></pre>
<p>I found this : </p>
<pre><code><% @user.find{|b| b.id == 1}%>
<%= @service.full_name%>
</code></pre>
<p>But didn't work and I don't know how to use it right in <code>index.html.erb</code></p>
| <p>Also you can take array element directly in template. For reason â if you need all another users to</p>
<pre class="lang-html prettyprint-override"><code><div class="super-user">
<%= @users[3].name %>
</div>
<div class="other-users">
<% @users.each do |u| %>
<a href="#">Destroy Him!</a>
<% end %>
</div>
</code></pre>
<p>If you don't need all another users, prefer to don't fetch them all. Use <code>find</code> or <code>find_by</code> methods e.g.</p>
<pre class="lang-ruby prettyprint-override"><code>@user = User.find(4) # finds user by id=4
</code></pre>
<p>or</p>
<pre><code>@user = User.find_by(name: 'user', admin: true) # finds by hash arguments
</code></pre>
<p>or even</p>
<pre><code># fetch direcly 3-th user from database
@user = User.order(:id).limit(1).offset(2).first
</code></pre>
<p><a href="http://guides.rubyonrails.org/active_record_querying.html" rel="nofollow">http://guides.rubyonrails.org/active_record_querying.html</a></p>
<p><a href="http://ruby-doc.org/core-2.3.1/Array.html" rel="nofollow">http://ruby-doc.org/core-2.3.1/Array.html</a></p>
|
How to create a Lisp FLI function corresponding to a C macro <p>I want to create a lisp function which corresponds to a macro in C.
e.g., there is one HIWORD in win32 API, which is defined as a macro in the header file.</p>
<p>I tried to define it as below but was told that HIWORD is unresolved.</p>
<pre><code>CL-USER 4 > (hiword #xFFFFFFFF)
Error: Foreign function HIWORD trying to call to unresolved external function "HIWORDW".
</code></pre>
<p>I just want to know how to create a wrapper for C macros like for C functions.</p>
<pre><code>(fli:define-c-typedef DWORD (:unsigned :long))
(fli:define-c-typedef WORD (:unsigned :short))
(fli:define-foreign-function
(HIWORD "HIWORD" :dbcs)
((dwVal dword))
:result-type word :calling-convention :stdcall)
</code></pre>
| <p>You cannot do this directly. C preprocessor macros are not preserved in the compilation process, i.e., there is simply no artifact in the generated object files, which would correspond to the C macro itself (though its expansion may be part of the object file multiple times). And since there is no artifact, there is nothing to bind to with FFI.</p>
<p>You can, however, provide a wrapper function</p>
<pre><code>#define HIGHWORD(x) /* whatever */
int
highword_wrapper(int x)
{
return HIGHWORD(x);
}
</code></pre>
<p>and this one can be used with FFI.</p>
|
How to Dump Headers From Response In php <p>Any one knows how to dump headers from from response in php while creating script</p>
<p>I am not able to pick uo the headers from response sent from first request.</p>
| <p>Reading request is very easy in Php. Try to use apache_response_headers function which dumps all HTTP response headers.</p>
<pre><code><?php
print_r(apache_response_headers());
?>
</code></pre>
<p>will print data like this </p>
<pre><code>Array
(
[Content-Location] => phpinfo.de.php
[Vary] => negotiate
[TCN] => choice
[X-Powered-By] => PHP/5.1.6
[Keep-Alive] => timeout=15, max=96
[Connection] => Keep-Alive
[Transfer-Encoding] => chunked
[Content-Type] => text/html
[Content-Language] => de
)
</code></pre>
<p>Reference
<a href="https://secure.php.net/manual/en/function.apache-response-headers.php" rel="nofollow">https://secure.php.net/manual/en/function.apache-response-headers.php</a> </p>
|
react-redux store not updating within onClick function <p>I'm experiencing this weird issue where my react-redux store is updating, but is not updating within the function that calls the actions.</p>
<p><code>this.props.active</code> is <code>undefined</code>, then I set it to an integer with <code>this.props.actions.activeSet(activeProc)</code>, but it remains <code>undefined</code> and enters the next if condition.</p>
<p>I know my app is working because everything else works with <code>this.props.active</code> having the correct value.</p>
<p>Is this supposed to happen?</p>
<p><strong>edit:</strong></p>
<p>After doing some testing, it appears that the state remains the same inside the onClick function.</p>
<p>All calls to <code>console.log(this.props)</code> made within the onClick function show no change to the state, but adding <code>setTimeout(() => {console.log(this.props)}, 1)</code> at the end to test shows that the state is being updated.</p>
<p>Other parts of the app are working as intended, with state changes applied immediately.</p>
<p>But I still don't understand what is going on.</p>
<p><strong>Component function code</strong></p>
<pre><code>() => {
console.log(this.props.active); // undefined
if (this.props.active === undefined && this.props.readyQueue.length > 0) {
let activeProc = this.props.readyQueue[0];
this.props.actions.readyPop();
this.props.actions.activeSet(activeProc); // set to an integer
this.props.actions.execStateSet("Running");
}
console.log(this.props.active); // still remains undefined
if (this.props.active === undefined) {
this.props.actions.execStateSet("Idle");
}
}
function mapStateToProps(state, props) {
return {
active: state.ProcessReducer.active,
};
}
</code></pre>
<p><strong>Action code</strong></p>
<pre><code>export const activeSet = (procId) => {
return {
type: 'ACTIVE_SET',
procId
}
}
</code></pre>
<p><strong>Reducer code</strong></p>
<pre><code>case 'ACTIVE_SET':
return Object.assign({}, state, {
active: action.procId
});
</code></pre>
| <p>Your Redux state updates synchronously with the dispatch of your action. Your reducer has executed by the time the <code>dispatch</code> call returns.</p>
<p>However, React isn't Redux. Redux tells React-Redux's wrapper component that the state has changed. This also happens before <code>dispatch</code> returns.</p>
<p>React-Redux then tells React that the component needs to be rerendered by calling <code>forceUpdate</code>. React then waits until it feels it's a good time to take care of that. I haven't looked, but it probably uses <code>setImmediate</code> or equivalent but it's async. This allows React to batch updates and maybe there are other reasons.</p>
<p>In any case, the React-Redux wrapper component will get rendered by React when the time comes and it'll use your <code>mapStateToProps</code> to distill the<code>props</code> out of the state and then passes them to React as props for your actual component. Then, when React feels it's an okay time, it calls your <code>render</code> method or function. It may do all kinds of things in before that, such as calling <code>componentWillReceiveProps</code> or rendering some other component that also needs rendering. In any case it's none of our business. React does its thing. But when your Render function is called, your props will now reflect the new state.</p>
<p>You shouldn't rely on new state in an <code>onClick</code> handler. The <code>onClick</code> should only call the bound action creator, which I guess is now more aptly called an action dispatcher. If something needs to be done with the new state, you should use Redux-Thunk middleware and create a thunked action creator. These have access to <code>getState</code> and if they don't perform any internal async stuff, then the entire action can actually be just as synchronous as a simple dispatch (not that you'd need that in a simple <code>onClick</code> handler).</p>
<p>Finally, React is very asynchronous in nature. Think of it as telling React what you want (component + props) and letting React take it from there. If React needs to know how to turn a component into DOM elements, it'll call your component's <code>render</code> function. How or when React does is thing is an implementation detail that doesn't concern us. </p>
|
@ng-bootstrap NgbDatepicker met "Can't bind to 'ngModel' since it isn't a known property of 'ngb-datepicker'" <p>I use <strong>@ng-bootstrap/ng-bootstrap</strong> and <strong>Angular2-cli</strong></p>
<p>with NgbDatepicker met errs :</p>
<p>NgModule:</p>
<pre><code>@NgModule({
imports: [CommonModule,NgbModule.forRoot()],
declarations: [TestComponent],
exports: [TestComponent]
})
</code></pre>
<p></p>
<p>component--</p>
<blockquote>
<p>export class TestComponent implements OnInit {</p>
<p>model: NgbDateStruct;</p>
<p>}</p>
</blockquote>
<p>and html--</p>
<blockquote>
<p><em>< ngb-datepicker #dp [(ngModel)]="model">< /ngb-datepicker></em></p>
</blockquote>
<p>when add TestModule to another module ,</p>
<pre><code>@NgModule({
imports: [SharedModule,LoginRoutingModule,TestModule],
declarations: [LoginComponent],
})
</code></pre>
<p>and html:</p>
<pre><code><app-test></app-test>
</code></pre>
<p>there is the err:</p>
<pre><code>error_handler.js:47EXCEPTION: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ngb-datepicker'.
1. If 'ngb-datepicker' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'ngb-datepicker' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("
<ngb-datepicker #dp [ERROR ->][(ngModel)]="model"></ngb-datepicker>
"): TestComponent@1:22ErrorHandler.handleError @ error_handler.js:47next @ application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:119onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
error_handler.js:52ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:52next @ application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:119onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
error_handler.js:53Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ngb-datepicker'.
1. If 'ngb-datepicker' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'ngb-datepicker' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("
<ngb-datepicker #dp [ERROR ->][(ngModel)]="model"></ngb-datepicker>
"): TestComponent@1:22
at resolvePromise (zone.js:429)
at zone.js:406
at ZoneDelegate.invoke (zone.js:203)
at Object.onInvoke (ng_zone_impl.js:43)
at ZoneDelegate.invoke (zone.js:202)
at Zone.run (zone.js:96)
at zone.js:462
at ZoneDelegate.invokeTask (zone.js:236)
at Object.onInvokeTask (ng_zone_impl.js:34)
at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:53next @ application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:119onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
zone.js:355Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ngb-datepicker'.
1. If 'ngb-datepicker' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'ngb-datepicker' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("
<ngb-datepicker #dp [ERROR ->][(ngModel)]="model"></ngb-datepicker>
"): TestComponent@1:22 ; Zone: angular ; Task: Promise.then ; Value: Error: Template parse errors:(â¦) Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'ngb-datepicker'.
1. If 'ngb-datepicker' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'ngb-datepicker' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("
<ngb-datepicker #dp [ERROR ->][(ngModel)]="model"></ngb-datepicker>
"): TestComponent@1:22
at TemplateParser.parse (http://localhost:4200/main.bundle.js:18077:19)
at RuntimeCompiler._compileTemplate (http://localhost:4200/main.bundle.js:42938:51)
at http://localhost:4200/main.bundle.js:42860:83
at Set.forEach (native)
at compile (http://localhost:4200/main.bundle.js:42860:47)
at ZoneDelegate.invoke (http://localhost:4200/main.bundle.js:99970:28)
at Object.onInvoke (http://localhost:4200/main.bundle.js:71761:37)
at ZoneDelegate.invoke (http://localhost:4200/main.bundle.js:99969:34)
at Zone.run (http://localhost:4200/main.bundle.js:99863:43)
at http://localhost:4200/main.bundle.js:100229:57consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
zone.js:357Error: Uncaught (in promise): Error: Template parse errors:(â¦)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
</code></pre>
| <p>You are missing FormsModule. Try importing like this-</p>
<pre><code>import {FormsModule} from '@angular/forms';
</code></pre>
<p>and use it in AppModule like this-</p>
<pre><code>@NgModule({
imports: [ BrowserModule, FormsModule, NgbModule ],
</code></pre>
<p>You can use ngbDatepicker like this too-</p>
<pre><code><input class="form-control" placeholder="yyyy-mm-dd" name="dp1" [(ngModel)]="newItem.EndTime" ngbDatepicker #d1="ngbDatepicker" required>
</code></pre>
<p>sample plunker: <a href="https://plnkr.co/edit/ZC3dOX9anbbNUMPEEd5W?p=preview" rel="nofollow">https://plnkr.co/edit/ZC3dOX9anbbNUMPEEd5W?p=preview</a></p>
<p>See if this helps.</p>
|
Convert gridview row values to string <p>If i have grid view that has the following data</p>
<pre><code>TechnicianID FirstName LastName
1 yasser jon
2 ali kamal
</code></pre>
<p>How can convert these grid row values into string in this below format</p>
<pre><code>yasser jon , ali kamal
</code></pre>
<p>GridView</p>
<pre><code><asp:GridView ID="gridtechnicians" CssClass="hidden" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="TechnicianID" HeaderText="TechnicianID" SortExpression="TechnicianID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
</Columns>
</asp:GridView>
</code></pre>
| <p>You can use <code>Foreach</code> loop on rows in your <code>DataGridView</code> and get values. This sample show how you can resolve your problem. </p>
<pre><code> string yourString = String.Empty;
foreach (GridViewRow rowDatos in this.gridtechnicians.Rows)
{
if (rowDatos.RowType == DataControlRowType.DataRow)
{
string firstName=gridtechnicians.DataKeys[rowDatos.RowIndex].Values[1].ToString();
string lastName=gridtechnicians.DataKeys[rowDatos.RowIndex].Values[2].ToString();
yourString += firstName+" "+lastName
}
}
</code></pre>
|
ORA-00923 error: FROM keyword not found where expected <p>When calculating retention on Oracle DB, I wrote this code:</p>
<pre><code>select
sessions.sessionDate ,
count(distinct sessions.visitorIdd) as active_users,
count(distinct futureactivity.visitorIdd) as retained_users,
count(distinct futureactivity.visitorIdd) / count(distinct sessions.visitorIdd)::float as retention
FROM sessions
left join sessions futureactivity on
sessions.visitorIdd=futureactivity.visitorIdd
and sessions.sessionDate = futureactivity.sessionDate - interval '3' day
group by 3;
</code></pre>
<p>but I always get the error: "ORA-00923: mot-clé FROM absent à l'emplacement prévu" (ORA-00923 FROM keyword not found where expected)
Can you help me guys? </p>
| <p>Oracle does not recognize <code>::</code> syntax of Postgres, so it complains of the missing <code>FROM</code> keyword not being found where expected.</p>
<p>Use a cast instead:</p>
<pre><code>count(distinct futureactivity.visitorIdd) / cast(count(distinct sessions.visitorIdd) as float) as retention
</code></pre>
|
Is there a more Pythonic/elegant way to expand the dimensions of a Numpy Array? <p>What I am trying to do right now is:</p>
<pre><code>x = x[:, None, None, None, None, None, None, None, None, None]
</code></pre>
<p>Basically, I want to expand my Numpy array by 9 dimensions. Or some N number of dimensions where N might not be known in advance!</p>
<p>Is there a better way to do this?</p>
| <p>One alternative approach could be with <code>reshaping</code> -</p>
<pre><code>x.reshape((-1,) + (1,)*N) # N is no. of dims to be appended
</code></pre>
<p>So, basically for the <code>None's</code> that correspond to singleton dimensions, we are using a shape of length <code>1</code> along those dims. For the first axis, we are using a shape of <code>-1</code> to <em>push all elements</em> into it.</p>
<p>Sample run -</p>
<pre><code>In [119]: x = np.array([2,5,6,4])
In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)
</code></pre>
|
Restrict Number of downloads by User IP Adrress in PHP <p>I'm building a PHP webpage which has a Button to download an image. I want to restrict unsigned user to download this image 3 times only.</p>
<p>I don't want to use neither Session nor Cookies because the user can delete his cookies!</p>
<p>I want to use IP, so I used the <code>$_SERVER</code> global variable but the problem here is the IP Address is changeable. It's dynamic and change every period of time.</p>
<p>So What should I do?</p>
| <p>Not all IPs are dynamic, this depends on the ISP. Your problem is identifying the user uniquely, which is impossible to do without requiring users to log in. No matter what you use, IPs, cookies, sessions, client side scripts to do browser fingerprinting or store tokens in the localStorage, a skilled used will always manage to get over your protections. </p>
<p>You can only make it difficult for the users:</p>
<ul>
<li>run a client side script to create browser finger print - <a href="https://github.com/Valve/fingerprintjs2" rel="nofollow">https://github.com/Valve/fingerprintjs2</a> - and send it to the server to help you identify the user</li>
<li>generate a server-side token and send it to the client and store it in the localStorage and send it back to the server</li>
<li>store the IP of the user in the DB</li>
<li>use session / cookies to add an extra layer of security</li>
<li>use an hidden iframe to load code from a different domain you own and add extra cookies from there (sometimes users don't delete all the cookies, just those for your site)</li>
<li>put captchas before the user can download an image so that you're not scrapped by bots</li>
</ul>
<p>Using a combination of all the above will make it annoying for an user to download pictures from your site without creating an user account, but not impossible. </p>
|
Rotate TextView from left edge instead of from center <p>I need to rotate TextView with image background. Here is my code</p>
<pre><code><TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@drawable/img_arrow_left"
android:gravity="center"
android:rotation="-90"
android:text="Swipe Vertically to Create a Bookmark"
android:textColor="#676767"
android:textSize="14sp"
</code></pre>
<p>Text rotated but it should be at the left side of screen, not at the center
<a href="https://i.stack.imgur.com/MLVm6.png" rel="nofollow"><img src="https://i.stack.imgur.com/MLVm6.png" alt="enter image description here"></a></p>
| <p>Try setting the <a href="https://developer.android.com/reference/android/view/View.html#attr_android:transformPivotX" rel="nofollow">transformPivotX</a> attribute to 0sp.</p>
<pre><code> android:transformPivotX="0sp"
</code></pre>
<p>It's supposed to set the <em>x location of the pivot point around which the view will rotate and scale</em>. Setting it to 0 puts the pivot point at the left edge of the view.</p>
|
Convert RGBA to NRGBA <p>I am trying to return the pixels that have changed and their color. The following func works fine, but it does not give me the 255,255,255 value i require. Is it possible to convert it to the format required?</p>
<p>I already looked at the documentation here -> <a href="https://golang.org/pkg/image/color/" rel="nofollow">https://golang.org/pkg/image/color/</a></p>
<p>I also tried different conversions manually, but i cannot get it to work. Does someone know how to convert this in golang?</p>
<pre><code>type Pixel struct {
x, y int
r, g, b, a uint32
}
func diffImages(imgOne *image.RGBA, imgTwo *image.RGBA) []Pixel {
var pixels []Pixel
bounds := imgOne.Bounds()
diff := false
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := imgOne.At(x, y).RGBA()
rt, gt, bt, at := imgTwo.At(x, y).RGBA()
if r != rt || g != gt || b != bt || a != at {
diff=true
}
if diff == true {
pixel := new(Pixel)
pixel.x = x
pixel.y = y
pixel.r = rt
pixel.g = gt
pixel.b = bt
pixel.a = at
pixels = append(pixels, *pixel)
}
diff = false
}
}
return pixels
}
</code></pre>
<p>If there is another better or faster way to get the required output than i am willing to accept.</p>
<p>Note: I am new to go.</p>
| <p>Do you mean this? I did other refactors, your code seemed needlessly complex. </p>
<p>I haven't tested this, didn't test images. </p>
<pre><code>// Pixels are pixels.
type Pixel struct {
x, y int
color color.NRGBA
}
func diffImages(imgOne image.RGBA, imgTwo image.RGBA) []Pixel {
var pixels []Pixel
bounds := imgOne.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
if !reflect.DeepEqual(imgOne.Pix, imgTwo.Pix) {
rt, gt, bt, at := imgTwo.At(x, y).RGBA()
pixel := new(Pixel)
pixel.x = x
pixel.y = y
pixel.color.R = uint8(rt)
pixel.color.G = uint8(gt)
pixel.color.B = uint8(bt)
pixel.color.A = uint8(at)
pixels = append(pixels, *pixel)
}
}
}
return pixels
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.