You can get the diff for a stash with "git show stash@{0}
" (or whatever the number of the stash is; see "git stash list"). It's easy to extract the section of the diff for a single file.
In base you can use ave
to get max
per group and compare this with pt
and get a logical vector to subset the data.frame
.
group[group$pt == ave(group$pt, group$Subject, FUN=max),]
# Subject pt Event
#3 1 5 2
#7 2 17 2
#9 3 5 2
Or compare it already in the function.
group[as.logical(ave(group$pt, group$Subject, FUN=function(x) x==max(x))),]
#group[ave(group$pt, group$Subject, FUN=function(x) x==max(x))==1,] #Variant
# Subject pt Event
#3 1 5 2
#7 2 17 2
#9 3 5 2
if its just two files and the sample rate is significantly high, you could just interleave them.
from scipy.io import wavfile
rate1,dat1 = wavfile.read(File1)
rate2,dat2 = wavfile.read(File2)
if len(dat2) > len(dat1):#swap shortest
temp = dat2
dat2 = dat1
dat1 = temp
output = dat1
for i in range(len(dat2)/2): output[i*2]=dat2[i*2]
wavfile.write(OUTPUT,rate,dat)
Your
$email_to = "[email protected], [email protected], [email protected]"
Needs to be a comma delimited list of email adrresses.
mail($email_to, $email_subject, $thankyou);
Consider this:
std::string str = "Hello " + "world"; // bad!
Both the rhs and the lhs for operator +
are char*
s. There is no definition of operator +
that takes two char*
s (in fact, the language doesn't permit you to write one). As a result, on my compiler this produces a "cannot add two pointers" error (yours apparently phrases things in terms of arrays, but it's the same problem).
Now consider this:
std::string str = "Hello " + std::string("world"); // ok
There is a definition of operator +
that takes a const char*
as the lhs and a std::string
as the rhs, so now everyone is happy.
You can extend this to as long a concatenation chain as you like. It can get messy, though. For example:
std::string str = "Hello " + "there " + std::string("world"); // no good!
This doesn't work because you are trying to +
two char*
s before the lhs has been converted to std::string
. But this is fine:
std::string str = std::string("Hello ") + "there " + "world"; // ok
Because once you've converted to std::string
, you can +
as many additional char*
s as you want.
If that's still confusing, it may help to add some brackets to highlight the associativity rules and then replace the variable names with their types:
((std::string("Hello ") + "there ") + "world");
((string + char*) + char*)
The first step is to call string operator+(string, char*)
, which is defined in the standard library. Replacing those two operands with their result gives:
((string) + char*)
Which is exactly what we just did, and which is still legal. But try the same thing with:
((char* + char*) + string)
And you're stuck, because the first operation tries to add two char*
s.
Moral of the story: If you want to be sure a concatenation chain will work, just make sure one of the first two arguments is explicitly of type std::string
.
Thanks @Harry the following code works for me:
.your-div{
vertical-align: bottom;
display: table-cell;
}
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
OR
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
Firstly, add path of visual studio common tools (c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools
) into the system path. To learn how to add a path into system path, please check this website:
http://www.computerhope.com/issues/ch000549.htm. You just need to this once.
After that, whenever you need, open a command line and execute vsvars32.bat
to add all required visual studio tools' paths into the system path.
Then, you can call nmake -f makefile.mak
PS: Path of visual studio common tools might be different in your system. Please change it accordingly.
You cannot append to an existing xlsx file with xlsxwriter
.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close()
which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()
).
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
On Debian, after much searching, this did the trick.
First:
sudo apt-get purge locales
Then:
sudo aptitude install locales
And the famous:
sudo dpkg-reconfigure locales
This rids the system of locales, then re-installs locales and downgrades libc6 from 2.19 to 2.13 which is the issue. Then it configures locales again.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
Go to IDE:
STEP 1: Open the menu item: click on Help then click on Edit Custom Properties
STEP 2: Set the parameter:
idea.max.intellisense.filesize= 999999999
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
Here is another simple solution in XAML:
XAML:
<TextBox>
<TextBox.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<!--text color-->
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Text" Value=""/>
</Trigger>
<Trigger Property="IsFocused" Value="False">
<!--placeholder color-->
<Setter Property="Foreground" Value="Gray"/>
<!--placeholder here-->
<Setter Property="Text" Value="Placeholder"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Resources>
</TextBox>
I doubt css understands left
by itself. You need to use it specifying position. You are using .css() correctly
position: relative/absolute/whatever;
left: 900px;
heres a fiddle of it working
and without the position here's what you get
Change your if statement to be like this - with quotes around -900px
var n = $("items").css("left");
if(n == '-900px'){
$(".items span").fadeOut("slow");
}
We can use either Pattern.compile("[0-9]+.[0-9]+")
or Pattern.compile("\\d+.\\d+")
. They have the same meaning.
the pattern [0-9] means digit. The same as '\d'. '+' means it appears more times. '.' for integer or float.
Try following code:
import java.util.regex.Pattern;
public class PatternSample {
public boolean containNumbersOnly(String source){
boolean result = false;
Pattern pattern = Pattern.compile("[0-9]+.[0-9]+"); //correct pattern for both float and integer.
pattern = Pattern.compile("\\d+.\\d+"); //correct pattern for both float and integer.
result = pattern.matcher(source).matches();
if(result){
System.out.println("\"" + source + "\"" + " is a number");
}else
System.out.println("\"" + source + "\"" + " is a String");
return result;
}
public static void main(String[] args){
PatternSample obj = new PatternSample();
obj.containNumbersOnly("123456.a");
obj.containNumbersOnly("123456 ");
obj.containNumbersOnly("123456");
obj.containNumbersOnly("0123456.0");
obj.containNumbersOnly("0123456a.0");
}
}
Output:
"123456.a" is a String
"123456 " is a String
"123456" is a number
"0123456.0" is a number
"0123456a.0" is a String
Another method for catching EXC_BAD_ACCESS exceptions before they happen is the static analyzer, in XCode 4+.
Run the static analyzer with Product > Analyze (shift+cmd+B). Clicking on any messages generated by the analyzer will overlay a diagram on your source showing the sequence of retains/releases of the offending object.
there might be a problem at your web hosting company from where you are testing the secure communication for gateway, that they might not allow you to do that.
also there might be a username, password that must be provided before connecting to remote host.
or your IP might need to be in the list of approved IP for the remote server for communication to initiate.
As I have noticed this error occurs under two circumstances,
so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)
Hope this helps.
Window -> New Window
This opens a new window and you can then open another project in it. You can use this as a workaround hopefully.
It actually allows you to work in same workspace.
Like this:
mongo <dbname> --eval "db.dropDatabase()"
More info on scripting the shell from the command line here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting
You need to start the Apache Tomcat services.
Win+R --> sevices.msc
Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost
.
Just to offer an update to the answer for people with API min 19, per the docs:
On Android 4.4 (API level 19) and higher, you have the additional option of using the ACTION_OPEN_DOCUMENT intent, which displays a system-controlled picker UI controlled that allows the user to browse all files that other apps have made available. From this single UI, the user can pick a file from any of the supported apps.
On Android 5.0 (API level 21) and higher, you can also use the ACTION_OPEN_DOCUMENT_TREE intent, which allows the user to choose a directory for a client app to access.
Open files using storage access framework - Android Docs
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.type = "image/*"
startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)
Use checkbox and change the input type accordingly.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int start,end;
Log.i("inside checkbox chnge",""+isChecked);
if(!isChecked){
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(new PasswordTransformationMethod());;
passWordEditText.setSelection(start,end);
}else{
start=passWordEditText.getSelectionStart();
end=passWordEditText.getSelectionEnd();
passWordEditText.setTransformationMethod(null);
passWordEditText.setSelection(start,end);
}
}
For my purpose, I wanted to scroll down more, keeping the windows position in mind. My solution was similar and used window.scrollY
driver.execute_script("window.scrollTo(0, window.scrollY + 200)")
which will go to the current y scroll position + 200
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
With urlsearchparams:
const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
A toast with custom background and view did the trick for me. I tested it in nexus 7 tablet and I noticed no fadein fadeout animation during looping. Heres the implementation:
public static void customToast(Context context, String message, int duration) {
for (int i = 0; i < duration; i++) {
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_layout, null);
TextView textViewToast = (TextView) view
.findViewById(R.id.textViewToast);
textViewToast.setText(message);
toast.setView(view);
toast.show();
}
}
Heres the custom textview used in above code:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textViewToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/fragment_background"
android:padding="8dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/blue" />
@drawable/fragment_background is making my toast have rounded corner as in kitkat version. You can add other views too in the file. Any modifications for improvement and comments are encouraged as I am planning to implement this in my live app.
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
use get
instead of load
// ...
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User) session.get(User.class, user_id);
} catch (Exception e) {
// ...
Download the latest gradle from https://gradle.org/install and set the gradle path upto bin in your PATH variable and export path in the directory you are working in
example : export PATH=/home/abc/android-sdk-linux/tools:/home/abc/android-sdk-linux/platform-tools:/home/abc/android-sdk-linux/tools:/home/abc/android-sdk-linux/platform-tools:/home/abc/Downloads/gradle-4.4.1/bin
I spent my whole day resolve this and ultimately this solution worked for me,
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
Edit:
Remove the wrong example.
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
This annotation is commonly used to eliminate NullPointerExceptions
. @Nullable
says that this parameter might be null
. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null
. If you would try to pass null
without an annotation the framework would refuse to do it's job.
What is more @Nullable
might be used with @NotNull
annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.
If you don't mind using your mouse a little bit:
This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell
and exit).
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:
np.einsum('ij->ij', a[a[:,1].argsort(),:])
This is an overkill for two dimensions and a[a[:,1].argsort()]
would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.
Output:
[[7 0 5]
[9 2 3]
[4 5 6]]
Edit your Catlina.bat so that your -Xmx settings are less than your physical memory
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS
$(document).ready(function(){
$("#a").mouseover(function(){
$("#b").css("background-color", "red");
});
});
A slightly nicer way of measuring execution time, is to use the rbenchmark package. This package (easily) allows you to specify how many times to replicate your test and would the relative benchmark should be.
See also a related question at stats.stackexchange
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
If your game has no server/site (e.g. if you develop for Gameroom like me) - add "https://apps.facebook.com/xxxxxxxxxxxxxxxxx" (put your app ID instead of "xxxxxxxxxxxx") to "Valid OAuth Redirect URIs".
The /g
modifier is used to perform a global match (find all matches rather than stopping after the first)
You can use \d
for digit, as it is shorter than [0-9]
.
JavaScript:
var s = "04.07.2012";
echo(s.replace(/\d/g, "X"));
Output:
XX.XX.XXXX
Though I'm using Mac OS 10.9, this solution may work for someone else as well, perhaps on Ubuntu.
In the XAMPP console, I only found that phpMyAdmin started working again after restarting everything including the Apache Web Server.
No problemo, now.
You can also intercept the form.submit event and reverse check before submit
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
this command gives you a description of your operating system
cat /etc/os-release
When a function is a part of a class, it's called a method.
C# is an OOP language and doesn't have functions that are declared outside of classes, that's why all functions in C# are actually methods.
Though, beside this formal difference, they are the same...
You can also put the tooltip onto one line by removing the "title":
this.chart = new Chart(ctx, {
type: this.props.horizontal ? 'horizontalBar' : 'bar',
options: {
legend: {
display: false,
},
tooltips: {
callbacks: {
label: tooltipItem => `${tooltipItem.yLabel}: ${tooltipItem.xLabel}`,
title: () => null,
}
},
},
});
modifying the proxy value under
[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]
doesnt need to restart ie
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
I had the same issue, and the answer was in the dmenu source code: the stest utility made for that purpose. You can compile the 'stest.c' and 'arg.h' files and it should work. There is a man page for the usage, that I put there for convenience:
STEST(1) General Commands Manual STEST(1)
NAME
stest - filter a list of files by properties
SYNOPSIS
stest [-abcdefghlpqrsuwx] [-n file] [-o file]
[file...]
DESCRIPTION
stest takes a list of files and filters by the
files' properties, analogous to test(1). Files
which pass all tests are printed to stdout. If no
files are given, stest reads files from stdin.
OPTIONS
-a Test hidden files.
-b Test that files are block specials.
-c Test that files are character specials.
-d Test that files are directories.
-e Test that files exist.
-f Test that files are regular files.
-g Test that files have their set-group-ID
flag set.
-h Test that files are symbolic links.
-l Test the contents of a directory given as
an argument.
-n file
Test that files are newer than file.
-o file
Test that files are older than file.
-p Test that files are named pipes.
-q No files are printed, only the exit status
is returned.
-r Test that files are readable.
-s Test that files are not empty.
-u Test that files have their set-user-ID flag
set.
-v Invert the sense of tests, only failing
files pass.
-w Test that files are writable.
-x Test that files are executable.
EXIT STATUS
0 At least one file passed all tests.
1 No files passed all tests.
2 An error occurred.
SEE ALSO
dmenu(1), test(1)
dmenu-4.6 STEST(1)
Well, the problem is that Git can't find KDiff3 in the %PATH%.
In a typical Unix installation all executables reside in several well-known locations (/bin/
, /usr/bin/
, /usr/local/bin/
, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe
:) ).
In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3
in a cmd
session and get KDiff3 running.
The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe
. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)
The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.
I met the same problem even using -ldl
.
Besides this option, source files need to be placed before libraries, see undefined reference to `dlopen'.
Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.
See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).
<script type="text/javascript">
// method 1
var images = {};
images['name'] = {};
images['family'] = {};
images[1] = {};
images['name'][5] = "Mehdi";
images['family'][8] = "Mohammadpour";
images['family']['ok'] = 123456;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][23] = 2602;
for (const [key1, value1] of Object.entries(images)){
for (const [key2, value2] of Object.entries(value1)){
console.log(`${key1} => ${key2}: ${value2}`);
}
}
console.log("=============================");
// method 2
var arr = [];
for(var x = 0; x < 5; x++){
arr[x] = [];
for(var y = 0; y < 5; y++){
arr[x][y] = x*y;
}
}
for(var i = 0; i < arr.length; i++) {
var cube = arr[i];
for(var j = 0; j < cube.length; j++) {
console.log("cube[" + i + "][" + j + "] = " + cube[j]);
}
}
</script>
You should always include the table name in the SQL query when dealing with associations.
Indeed if another table has the user_id
column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).
So, in your example:
GroupUser.where("groups_users.user_id != ?", me)
Or a bit more verbose:
GroupUser.where("#{table_name}.user_id IS NOT ?", me)
Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:
GroupUser.where(user: me)
In Rails 4, as said by @dr4k3, the query method not
has been added:
GroupUser.where.not(user: me)
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
<androidx.appcompat.widget.SwitchCompat
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
app:track="@drawable/track"
android:thumb="@drawable/thumb"
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false"
android:drawable="@drawable/switch_thumb_false"/>
<item android:state_checked="true"
android:drawable="@drawable/switch_thumb_true"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<size android:width="24dp" android:height="12dp" />
<solid android:color="#EFE0BB" />
<corners android:radius="6dp" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<size android:width="24dp" android:height="12dp" />
<solid android:color="@color/colorPrimary" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#EFE0BB" />
<size
android:width="10dp"
android:height="10dp" />
<stroke
android:width="2dp"
android:color="@color/colorPrimary" />
</shape>
</item>
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="oval">
<solid android:color="@color/colorPrimary"/>
<size android:height="12dp"
android:width="12dp"/>
<stroke android:color="#EFE0BB"
android:width="2dp"/>
</shape>
</item>
</layer-list>
/*
Input from command line using atoi, and strtol
*/
#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol
//strtol - converts a string to a long int
//atoi - converts string to an int
int main(int argc, char *argv[]){
char *p;//used in strtol
int i;//used in for loop
long int longN = strtol( argv[1],&p, 10);
printf("longN = %ld\n",longN);
//cast (int) to strtol
int N = (int) strtol( argv[1],&p, 10);
printf("N = %d\n",N);
int atoiN;
for(i = 0; i < argc; i++)
{
//set atoiN equal to the users number in the command line
//The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
atoiN = atoi(argv[i]);
}
printf("atoiN = %d\n",atoiN);
//-----------------------------------------------------//
//Get string input from command line
char * charN;
for(i = 0; i < argc; i++)
{
charN = argv[i];
}
printf("charN = %s\n", charN);
}
Hope this helps. Good luck!
I have this grid class that can be used as a simple matrix if you don't need any mathematical operators.
/**
* Represents a grid of values.
* Indices are zero-based.
*/
template<class T>
class GenericGrid
{
public:
GenericGrid(size_t numRows, size_t numColumns);
GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue);
const T & get(size_t row, size_t col) const;
T & get(size_t row, size_t col);
void set(size_t row, size_t col, const T & inT);
size_t numRows() const;
size_t numColumns() const;
private:
size_t mNumRows;
size_t mNumColumns;
std::vector<T> mData;
};
template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns):
mNumRows(numRows),
mNumColumns(numColumns)
{
mData.resize(numRows*numColumns);
}
template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue):
mNumRows(numRows),
mNumColumns(numColumns)
{
mData.resize(numRows*numColumns, inInitialValue);
}
template<class T>
const T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx) const
{
return mData[rowIdx*mNumColumns + colIdx];
}
template<class T>
T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx)
{
return mData[rowIdx*mNumColumns + colIdx];
}
template<class T>
void GenericGrid<T>::set(size_t rowIdx, size_t colIdx, const T & inT)
{
mData[rowIdx*mNumColumns + colIdx] = inT;
}
template<class T>
size_t GenericGrid<T>::numRows() const
{
return mNumRows;
}
template<class T>
size_t GenericGrid<T>::numColumns() const
{
return mNumColumns;
}
try this, in my case the port number for the created object wasn't available so I came up with this
IPEndPoint endPoint;
int port = 1;
while (true)
{
try
{
endPoint = new IPEndPoint(IPAddress.Any, port);
break;
}
catch (SocketException)
{
port++;
}
}
For those who get Package not found
error try sudo apt-get install php7-intl
then run composer install
in your project directory.
fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.
String path = "Your_Path";
File f = new File(path);
if (f.isDirectory()){
}else if(f.isFile()){
}
A three line solution, but works quite well:
int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
target_list.add(random_array[i]);
}
If using Visual Studio Code** with Kotlin extension, go to the plugin management Crtl + Shift + x, type kotlin and click on manage (the little gear) >> Configure Extension Settings
on Kotlin >> Compiler >> Jvm:Target - type the java version. In my situation just typed 1.8
And then restart :-)
** vscode or just 'code' for linux
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
SELECT
p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, r.command,
p.program_name, text
FROM
sys.dm_exec_requests AS r,
master.dbo.sysprocesses AS p
CROSS APPLY sys.dm_exec_sql_text(p.sql_handle)
WHERE
p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid
I got this exception when in the Java Client Application I was serializing a JSON like this
String json = mapper.writeValueAsString(contentBean);
and on the Server Side I was using Spring Boot as REST Endpoint. Exception was:
nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xaa
My problem was, that I was not setting the correct encoding on the HTTP Client. This solved my problem:
updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity= new StringEntity(json, "UTF-8");
updateRequest.setEntity(entity);
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
I was also wondering how to store it cleanly in a variable. As using
char c = '•';
is not very good practice (I guess). I found out the following way of storing it in a variable
char c = (char)0x2022;// or 0x25cf depending on the one you choose
or even cleaner
char c = '\u2022';// or "\u25cf"
https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx
same for strings
string s = "\u2022";
In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.
Either you will
v <- c
)v, ok <- c
)v, ok <- c
)v <- c
)Only the last one technically doesn't read from the channel, but that's of little use.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Many great answers, here is my 2 cents with exact functionality as requested in the question.
Plus it should be a bit easier to read and debug.
Code is tested up to 128 chars of input.
Tested on Arduino uno r3 (Arduino IDE 1.6.8)
Functionality:
Commands:
Note: Remember to change baud rate based on your board speed.
// Turns Arduino onboard led (pin 13) on or off using serial command input.
// Pin 13, a LED connected on most Arduino boards.
int const LED = 13;
// Serial Input Variables
int intLoopCounter = 0;
String strSerialInput = "";
// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.
pinMode(LED, OUTPUT);
// initialize serial port
Serial.begin(250000); // CHANGE BAUD RATE based on the board speed.
// initialized
Serial.println("Initialized.");
}
// the loop routine runs over and over again forever:
void loop()
{
// Slow down a bit.
// Note: This may have to be increased for longer strings or increase the iteration in GetPossibleSerialData() function.
delay(1);
CheckAndExecuteSerialCommand();
}
void CheckAndExecuteSerialCommand()
{
//Get Data from Serial
String serialData = GetPossibleSerialData();
bool commandAccepted = false;
if (serialData.startsWith("LED.ON"))
{
commandAccepted = true;
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
}
else if (serialData.startsWith("LED.OFF"))
{
commandAccepted = true;
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
}
else if (serialData != "")
{
Serial.println();
Serial.println("*** Command Failed ***");
Serial.println("\t" + serialData);
Serial.println();
Serial.println();
Serial.println("*** Invalid Command ***");
Serial.println();
Serial.println("Try:");
Serial.println("\tLED.ON");
Serial.println("\tLED.OFF");
Serial.println();
}
if (commandAccepted)
{
Serial.println();
Serial.println("*** Command Executed ***");
Serial.println("\t" + serialData);
Serial.println();
}
}
String GetPossibleSerialData()
{
String retVal;
int iteration = 10; // 10 times the time it takes to do the main loop
if (strSerialInput.length() > 0)
{
// Print the retreived string after looping 10(iteration) ex times
if (intLoopCounter > strSerialInput.length() + iteration)
{
retVal = strSerialInput;
strSerialInput = "";
intLoopCounter = 0;
}
intLoopCounter++;
}
return retVal;
}
void serialEvent()
{
while (Serial.available())
{
strSerialInput.concat((char) Serial.read());
}
}
If you're already using jQuery, you could look at using the jQuery Number Format plugin.
The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.
$.number( 123, 2 ); // Returns '123.00'
You can also get jQuery Number Format from GitHub.
I found that this question was still relevant but not clearly answered in my case.
Using SQL Server 2012 with an orphaned SQL_USER this was the fix;
USE databasename -- The database I had recently attached
EXEC sp_change_users_login 'Report' -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'
One fairly simple alternative is to invoke PowerShell via a shortcut. There is a shortcut property labeled "Start in" that says what directory(folder) to use when the shortcut is invoked.
If the Start In box is blank, it means use the current directory.
When you first create a shortcut to PowerShell in the usual way, the start in box specifies the home directory. If you blank out the start in box, you now have a shortcut to powershell that opens PS in the current directory, whatever that is.
If you now copy this shortcut to the target directory, and use explorer to invoke it, you'll start a PS that's pointed at the target directory.
There's already an accepted answer to this question, but I offer this as another way.
Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.
note I changed the varchar2(32000) to CLOB
set serveroutput ON
CREATE TABLE testclob
(
id NUMBER,
c CLOB,
d VARCHAR2(4000)
);
DECLARE
reallybigtextstring CLOB := '123';
i INT;
BEGIN
WHILE Length(reallybigtextstring) <= 60000 LOOP
reallybigtextstring := reallybigtextstring
|| '000000000000000000000000000000000';
END LOOP;
INSERT INTO testclob
(id,
c,
d)
VALUES (0,
reallybigtextstring,
'done');
dbms_output.Put_line('I have finished inputting your clob: '
|| Length(reallybigtextstring));
END;
/
SELECT *
FROM testclob;
"I have finished inputting your clob: 60030"
You can use
$('#li_from_date').appendDtpicker({
"dateOnly": true,
"autodateOnStart": false,
"dateFormat": "DD/MM/YYYY",
"closeOnSelected": true,
"futureonly": true
});
Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:
Have a look at config.sample.inc.php: you will find examples of the configuration directives that you should copy to your config.inc.php (copy the missing ones). Then, have a look at examples/create_tables.sql which will help you create the missing tables.
The complete documentation for this is available at http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.
If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:
.profile
, or whatever is appropriate, and put /usr/local/bin
at the start
of your PATH
so that Homebrew binaries are found before system binariesbrew install python
- this installs a newer version of python in /usr/local
pip install pandas
This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.
Select Product
from formula bar in your answer cell.
Select cells you want to multiply.
My two cents.
Python 3.8.1, Windows 10, 64-bit.
sys.exit()
does not work directly for me.
I have several nexted loops.
First I declare a boolean variable, which I call immediateExit
.
So, in the beginning of the program code I write:
immediateExit = False
Then, starting from the most inner (nested) loop exception, I write:
immediateExit = True
sys.exit('CSV file corrupted 0.')
Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:
if immediateExit:
sys.exit('CSV file corrupted 1.')
Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits.
'CSV file corrupted 1.5.'
In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.
And following the gradual sys.exit-ing from all the loops I manage to do it.
Full code: (some changes were needed because it is proprietory code for internal tasks):
immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date
end_date_in_working_days = False
while not end_date_in_working_days:
try:
end_day_position = working_days.index(end_date)
end_date_in_working_days = True
except ValueError: # try statement from end_date in workdays check
print(current_date_and_time())
end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
print('New end date: ', end_date, '\n')
continue
csv_filename = 'test.csv'
csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
try:
with open(csv_filename, 'r') as file:
print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
last_line = file.readlines()[-1]
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
resumedDate = start_date
if last_line == csv_headers:
pass
elif start_date not in working_days:
print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
immediateExit = True
sys.exit('CSV file corrupted 0.')
else:
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
print('\nLast date:', start_date)
file.seek(0) # setting the cursor at the beginnning of the file
lines = file.readlines() # reading the file contents into a list
count = 0 # nr. of lines with last date
for line in lines: #cycling through the lines of the file
if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
count = count + 1
if immediateExit:
sys.exit('CSV file corrupted 1.')
for iter in range(count): # removing the lines with last date
lines.pop()
print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))
if immediateExit:
sys.exit('CSV file corrupted 1.2.')
with open(csv_filename, 'w') as file:
print('\nFile', csv_filename, 'open for writing')
file.writelines(lines)
print('\nRemoving', count, 'lines from', csv_filename)
fileExists = True
except:
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
with open(csv_filename, 'w') as file:
file.write(csv_headers)
fileExists = False
if immediateExit:
sys.exit('CSV file corrupted 2.')
Why use deflate instead of gzip for text files served by Apache?
The simple answer is don't.
RFC 2616 defines deflate as:
deflate The "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951
The zlib format is defined in RFC 1950 as :
0 1
+---+---+
|CMF|FLG| (more-->)
+---+---+
0 1 2 3
+---+---+---+---+
| DICTID | (more-->)
+---+---+---+---+
+=====================+---+---+---+---+
|...compressed data...| ADLER32 |
+=====================+---+---+---+---+
So, a few headers and an ADLER32 checksum
RFC 2616 defines gzip as:
gzip An encoding format produced by the file compression program "gzip" (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC.
RFC 1952 defines the compressed data as:
The format presently uses the DEFLATE method of compression but can be easily extended to use other compression methods.
CRC-32 is slower than ADLER32
Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter).
So ... we have 2 compression mechanisms that use the same algorithm for compression, but a different algorithm for headers and checksum.
Now, the underlying TCP packets are already pretty reliable, so the issue here is not Adler 32 vs CRC-32 that GZIP uses.
Turns out many browsers over the years implemented an incorrect deflate algorithm. Instead of expecting the zlib header in RFC 1950 they simply expected the compressed payload. Similarly various web servers made the same mistake.
So, over the years browsers started implementing a fuzzy logic deflate implementation, they try for zlib header and adler checksum, if that fails they try for payload.
The result of having complex logic like that is that it is often broken. Verve Studio have a user contributed test section that show how bad the situation is.
For example: deflate works in Safari 4.0 but is broken in Safari 5.1, it also always has issues on IE.
So, best thing to do is avoid deflate altogether, the minor speed boost (due to adler 32) is not worth the risk of broken payloads.
Try the QuickTime Player! Heres my JavaScript that generates the embedded object on a web page and plays the stream:
//SET THE RTSP STREAM ADDRESS HERE
var address = "rtsp://192.168.0.101/mpeg4/1/media.3gp";
var output = '<object width="640" height="480" id="qt" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">';
output += '<param name="src" value="'+address+'">';
output += '<param name="autoplay" value="true">';
output += '<param name="controller" value="false">';
output += '<embed id="plejer" name="plejer" src="/poster.mov" bgcolor="000000" width="640" height="480" scale="ASPECT" qtsrc="'+address+'" kioskmode="true" showlogo=false" autoplay="true" controller="false" pluginspage="http://www.apple.com/quicktime/download/">';
output += '</embed></object>';
//SET THE DIV'S ID HERE
document.getElementById("the_div_that_will_hold_the_player_object").innerHTML = output;
If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.
Here is an example of how to use it:
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
presentViewController(refreshAlert, animated: true, completion: nil)
As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/
Swift 3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5.3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Another option is to do like this:
<html>
<body>
<?php
//...php code...
?>
<script type="text/javascript">
document.write("Hello World!");
</script>
<?php
//....php code...
?>
</body>
</html>
and if you want to use PHP inside your JavaScript, do like this:
<html>
<body>
<?php
$text = "Hello World!";
?>
<script type="text/javascript">
document.write("<?php echo $text ?>");
</script>
<?php
//....php code...
?>
</body>
</html>
Hope this can help.
size
is inconsistent across different browsers and their possible font settings.
The width
style set in px will at least be consistent, modulo box-sizing issues. You might also want to set the style in ‘em’ if you want to size it relative to the font (though again, this will be inconsistent unless you set the input's font
family and size explicitly), or ‘%’ if you are making a liquid-layout form. Either way, a stylesheet is probably preferable to the inline style
attribute.
You still need size
for <select multiple>
to get the height to line up with the options properly. But I'd not use it on an <input>
.
I subclassed namedtuple and overrode the __new__
method:
from collections import namedtuple
class Node(namedtuple('Node', ['value', 'left', 'right'])):
__slots__ = ()
def __new__(cls, value, left=None, right=None):
return super(Node, cls).__new__(cls, value, left, right)
This preserves an intuitive type hierarchy, which the creation of a factory function disguised as a class does not.
You need DATE_ADD/DATE_SUB
:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
should work.
I'm posting this for people searching for an answer when using MySQL and Java Spring Boot JPA, like @immanuelRocha says, only have too @CreationTimeStamp to the @Column in Spring, and in MySQL set the default value to "CURRENT_TIMESTAMP".
In Spring add just the line :
@Column(name = "insert_date")_x000D_
@CreationTimestamp_x000D_
private Timestamp insert_date;
_x000D_
This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET
@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1 ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.
Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.
But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.
You can use this free service: https://www.smtpjs.com
<script src="https://smtpjs.com/v2/smtp.js"></script>
Email.send(
"[email protected]",
"[email protected]",
"This is a subject",
"this is the body",
"smtp.yourisp.com",
"username",
"password"
);
GIFImageView
public class GifImageView extends ImageView {
Movie movie;
InputStream inputStream;
private long mMovieStart;
public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public GifImageView(Context context) {
super(context);
}
public GifImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
inputStream = context.getResources()
.openRawResource(R.drawable.thunder);
byte[] array = streamToBytes(inputStream);
movie = Movie.decodeByteArray(array, 0, array.length);
}
private byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
byteArrayOutputStream.write(buffer, 0, len);
return byteArrayOutputStream.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long now = SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (movie != null) {
int dur = movie.duration();
if (dur == 0) {
dur = 3000;
}
int relTime = (int) ((now - mMovieStart) % dur);
movie.setTime(relTime);
movie.draw(canvas, getWidth() - 200, getHeight() - 200);
invalidate();
}
}
}
In XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="abc" />
<com.example.apptracker.GifImageView
android:id="@+id/gifImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
In Java File
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GifImageView gifImageView = (GifImageView) findViewById(R.id.gifImageView1);
if (Build.VERSION.SDK_INT >= 11) {
gifImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
}
We need to use gifImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
as when hardware accelerated enabled, GIF image not work on those device. Hardware accelerated is enabled on devices above(4.x).
For Access, you can use the SQL Select query I present here:
For example you have this table:
888 || T800 ARNOLD || [email protected]
123 || JOHN CONNOR || [email protected]
125 || SARAH CONNOR ||[email protected]
And you need to select only distinct mails. You can do it with this:
SQL SELECT:
SELECT MAX(p.CLIENTE) AS ID_CLIENTE
, (SELECT TOP 1 x.NOMBRES
FROM Rep_Pre_Ene_MUESTRA AS x
WHERE x.MAIL=p.MAIL
AND x.CLIENTE=(SELECT MAX(l.CLIENTE) FROM Rep_Pre_Ene_MUESTRA AS l WHERE x.MAIL=l.MAIL)) AS NOMBRE,
p.MAIL
FROM Rep_Pre_Ene_MUESTRA AS p
GROUP BY p.MAIL;
You can use this to select the maximum ID, the correspondent name to that maximum ID , you can add any other attribute that way. Then at the end you put the distinct column to filter and you only group it with that last distinct column.
This will bring you the maximum ID with the correspondent data, you can use min or any other functions and you replicate that function to the sub-queries.
This select will return:
888 || T800 ARNOLD || [email protected]
125 || SARAH CONNOR ||[email protected]
Remember to index the columns you select and the distinct column must have not numeric data all in upper case or in lower case, or else it won't work. This will work with only one registered mail as well. Happy coding!!!
This can be expressed in pseudocode as:
while(n > 0):
remainder = n%2;
n = n/2;
Insert remainder to front of a list or push onto a stack
Print list or stack
If you are willing to use custom table header as table header, try the followings....
Updated for swift 3.0
Step 1
Create UITableViewHeaderFooterView for custom header..
import UIKit
class MapTableHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var testView: UIView!
}
Step 2
Add custom header to UITableView
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//register the header view
let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
}
extension BranchViewController : UITableViewDelegate{
}
extension BranchViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView
return headerView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
// retuen no of rows in sections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// retuen your custom cells
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func numberOfSections(in tableView: UITableView) -> Int {
// retuen no of sections
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// retuen height of row
}
}
This worked for me on Swift 5
let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)
select
Field1, Field2...
from
Table1
order by
isnumeric(Field1) desc,
case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,
Field1
This will return values in the order you gave in your question.
Performance won't be too great with all that casting going on, so another approach is to add another column to the table in which you store an integer copy of the data and then sort by that first and then the column in question. This will obviously require some changes to the logic that inserts or updates data in the table, to populate both columns. Either that, or put a trigger on the table to populate the second column whenever data is inserted or updated.
iter->first
and iter->second
are variables, you are attempting to call them as methods.
Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
The easiest solution to this is to use rgba
as the color: border-color: rgba(0,0,0,0);
That is fully transparent border color.
Here is more compact version of the most successful answer:
create table #tbl(
name nvarchar(128),
rows varchar(50),
reserved varchar(50),
data varchar(50),
index_size varchar(50),
unused varchar(50)
)
exec sp_msforeachtable 'insert into #tbl exec sp_spaceused [?]'
select * from #tbl
order by convert(int, substring(data, 1, len(data)-3)) desc
drop table #tbl
You may use bellow like.
If you want use json array:
Create A class named Model like bellow
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
In sevlet getMethod you can use like bellow
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//begin get data from databse or other source
List<Model> list = new ArrayList<>();
Model model = new Model();
model.setId("101");
model.setName("Enamul Haque");
list.add(model);
Model model1 = new Model();
model1.setId("102");
model1.setName("Md Mohsin");
list.add(model1);
//End get data from databse or other source
try {
JSONArray ja = new JSONArray();
for (Model m : list) {
JSONObject jSONObject = new JSONObject();
jSONObject.put("id", m.getId());
jSONObject.put("name", m.getName());
ja.add(jSONObject);
}
System.out.println(" json ja = " + ja);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(ja.toString());
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Output:
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
I you want json Object just use like:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
JSONObject json = new JSONObject();
json.put("id", "108");
json.put("name", "Enamul Haque");
System.out.println(" json JSONObject= " + json);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception e) {
e.printStackTrace();
}
}
Above function Output:
{"name":"Enamul Haque","id":"108"}
Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git
An example using .remove()
:
<p>Remove LI's from list</p>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
<p>END</p>
setTimeout(function(){$('ul li').remove();},1000);
http://jsfiddle.net/userdude/ZAd2Y/
Also, .empty()
should have worked.
I agree httpclient is something of a standard - but I guess you are looking for options so...
Restlet provides a http client specially designed for interactong with Restful web services.
Example code:
Client client = new Client(Protocol.HTTP);
Request r = new Request();
r.setResourceRef("http://127.0.0.1:8182/sample");
r.setMethod(Method.GET);
r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
client.handle(r).getEntity().write(System.out);
See http://www.restlet.org/ for more details
You could write a custom template filter to do this in a half-dozen lines of code:
from django.template import Library
register = Library()
@register.filter
def is_false(arg):
return arg is False
Then in your template:
{% if myvar|is_false %}...{% endif %}
Of course, you could make that template tag much more generic... but this suits your needs specifically ;-)
If the order is not important, you should use set.difference
. However, if you want to retain order, a simple list comprehension is all it takes.
result = [a for a in A if a not in subset_of_A]
EDIT: As delnan says, performance will be substantially improved if subset_of_A
is an actual set
, since checking for membership in a set
is O(1) as compared to O(n) for a list.
A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A
result = [a for a in A if a not in subset_of_A]
I'm using following markup and had encoutered the same problem:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Here I have used the following logic:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
In terms of the exact question, I can see that working as follows:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
or of course the other way around:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Hope that helps.
You could also try nextBoolean()
-Method
Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm
You can prefix the size requirement with -
to left-justify:
sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))
Well you can open an app by calling openURL:
or openURL:options:completionHandler:
(iOS 10 onwards) directly without making the conditional check canOpenURL:
.
Please read the discussion section in Apple doc for canOpenURL: method which says:
the openURL: method is not constrained by the
LSApplicationQueriesSchemes
requirement.
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
print("to_id:", dest.get('id', 'null'))
Try it:
>>> getTargetIds(jsonData)
to_id: 1543
to_id: null
Or, if you just want to skip over values missing ids instead of printing 'null'
:
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
if 'id' in to_id:
print("to_id:", dest['id'])
So:
>>> getTargetIds(jsonData)
to_id: 1543
Of course in real life, you probably don't want to print
each id, but to store them and do something with them, but that's another issue.
This is the way it worked for me, because with other methods the form was sent empty:
<form name="yourform" id="yourform" method="POST" action="yourpage.html">
<input type=hidden name="data" value="yourdata">
<input type="submit" id="send" name="send" value="Send">
</form>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.createElement('form').submit.call(document.getElementById('yourform'));
});
</script>
Just declare a method,e.g:if ur button id is button1 then,
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
}
});
If you want to make the imageview1 visible then in that method write:
imageview1.setVisibility(ImageView.VISIBLE);
Your code assumes the existence of something:
$user = $_POST["username"];
PHP is letting you know that there is no "username" in the $_POST
array. In this instance, you would be safer checking to see if the value isset()
before attempting to access it:
if ( isset( $_POST["username"] ) ) {
/* ... proceed ... */
}
Alternatively, you could hi-jack the ||
operator to assign a default:
$user = $_POST["username"] || "visitor" ;
As long as the user's name isn't a falsy value, you can consider this method pretty reliable. A much safer route to default-assignment would be to use the ternary operator:
$user = isset( $_POST["username"] ) ? $_POST["username"] : "visitor" ;
This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.
The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th
, td
or something else.
tr > * + * {
padding-left: 4em;
}
_x000D_
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
_x000D_
One more way to check existence of an element in a List
var result = myList.Exists(users => users.Equals("Vijai"))
This is the simplest I could reduce it to:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</body>
</html>
SCREENSHOT
There is some closure magic happening when passing the callback argument to the addListener
method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:
You need to use the global statement so that you are modifying the global variable counter, instead of a local variable:
counter = 0
def increment():
global counter
counter += 1
increment()
If the enclosing scope that counter
is defined in is not the global scope, on Python 3.x you could use the nonlocal statement. In the same situation on Python 2.x you would have no way to reassign to the nonlocal name counter
, so you would need to make counter
mutable and modify it:
counter = [0]
def increment():
counter[0] += 1
increment()
print counter[0] # prints '1'
To properly handle SSL certificate validation and avoid application rejection from Google according new Security Policy, Change your code to invoke SslErrorHandler.proceed() whenever the certificate presented by the server meets your expectations, and invoke SslErrorHandler.cancel() otherwise.
For example, I add an alert dialog to make user have confirmed and seems Google no longer shows warning.
@Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = "SSL Certificate error.";
switch (error.getPrimaryError()) {
case SslError.SSL_UNTRUSTED:
message = "The certificate authority is not trusted.";
break;
case SslError.SSL_EXPIRED:
message = "The certificate has expired.";
break;
case SslError.SSL_IDMISMATCH:
message = "The certificate Hostname mismatch.";
break;
case SslError.SSL_NOTYETVALID:
message = "The certificate is not yet valid.";
break;
}
message += " Do you want to continue anyway?";
builder.setTitle("SSL Certificate Error");
builder.setMessage(message);
builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
After this changes it will not show warning.
I followed these steps and it worked perfectly
Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
according to GSON User guide, you cannot.
Collections Limitations
Can serialize collection of arbitrary objects but can not deserialize from it. Because there is no way for the user to indicate the type of the resulting object
in your case you just need to
git diff HEAD^ HEAD^2
or just hash for you commit:
git diff 0e1329e55^ 0e1329e55^2
you can do this by setting the date of expiry to yesterday.
My new set of posts about cookies in JavaScript could help you.
http://www.markusnordhaus.de/2012/01/20/using-cookies-in-javascript-part-1/
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep('/hello/i', $haystack);
print_r($matches);
Output
Array
(
[1] => say hello
[2] => hello stackoverflow
[3] => hello world
)
Just read the rabbitmq tutorial. You publish message to exchange, not to queue; it is then routed to appropriate queues. In your case, you should bind separate queue for each consumer. That way, they can consume messages completely independently.
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
I had the same problem as you, Noboby can understand me, But I solved it in this way.
SELECT NAME, TELEFONE, DATA
FROM [sheet1$a1:q633]
WHERE NAME IN (SELECT * FROM [sheet2$a1:a2])
you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.
It is not at all obvious why one would want to concatenate the (decimal) "ascii values". What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.
>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05']
>>> ["".join("%d" % ord(c) for c in s) for s in tests]
['104105', '72105', '7273', '104105']
Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.
>>> ["".join("%03d" % ord(c) for c in s) for s in tests]
['104105', '072105', '072073', '010041000005']
>>> [" ".join("%d" % ord(c) for c in s) for s in tests]
['104 105', '72 105', '72 73', '10 41 0 5']
>>> ["".join("%02x" % ord(c) for c in s) for s in tests]
['6869', '4869', '4849', '0a290005']
>>>
Note no such problems.
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
you don't need to set the width of header in css, just put the background image as center using this code:
background: url("images/logo.png") no-repeat top center;
or you can just use img
tag and put align="center"
in the div
Building on Demircan Celebi's solution; I wanted the tab to open when modifying the url and open tab without having to reload the page from the server.
<script type="text/javascript">
$(function() {
openTabHash(); // for the initial page load
window.addEventListener("hashchange", openTabHash, false); // for later changes to url
});
function openTabHash()
{
console.log('openTabHash');
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
}
// With HTML5 history API, we can easily prevent scrolling!
$('.nav-tabs a').on('shown.bs.tab', function (e) {
if(history.pushState) {
history.pushState(null, null, e.target.hash);
} else {
window.location.hash = e.target.hash; //Polyfill for old browsers
}
})
}
</script>
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
This may work for you:
select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
from table2
group by t2.Chromosome, t2.Locus
having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus
You are getting this exception because your AWS SDK is unable to load your credentials. What you should do is goto Preferences then goto AWS and add your secret key and access key. So that your project can retrieve both keys.
Macmade's solution doesn't work for me anymore on my Jekyll instance on Github Pages anymore but I found this solution on an issue for the kramdown github repo. For OP's example it would look like this:
1. item 1
2. item 2
```
Code block
```
{:start="3"}
3. item 3
Solved my issues handily.
This is (rather ridiculously) a private API.
The following two methods are private and sent to the UITableView's delegate:
-(NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath;
They are pretty self explanatory.
The accepted answer here is problematic, because there is no guarantee that an image will have any sort of interactive shell. For example, the drone/drone image contains on a single command /drone
, and it has an ENTRYPOINT
as well, so this will fail:
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
And this will fail:
$ docker run --rm -it --entrypoint sh drone/drone
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"sh\": executable file not found in $PATH".
This is not an uncommon configuration; many minimal images contain only the binaries necessary to support the target service. Fortunately, there are mechanisms for exploring an image filesystem that do not depend on the contents of the image. The easiest is probably the docker export
command, which will export a container filesystem as a tar archive. So, start a container (it does not matter if it fails or not):
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
Then use docker export
to export the filesystem to tar
:
$ docker export $(docker ps -lq) | tar tf -
The docker ps -lq
there means "give me the id of the most recent docker container". You could replace that with an explicit container name or id.
If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:
Set a breakpoint on malloc_error_break() by opening the Breakpoint Navigator (View->Navigators->Show Breakpoint Navigator or ?8), clicking the plus button in the lower left corner, and selecting "Add Symbolic Breakpoint". In the popup that comes up, enter malloc_error_break
in the Symbol field, then click Done.
EDIT: openfrog added a screenshot and indicated that he's already tried these steps without success after I posted my answer. With that edit, I'm not sure what to say. I haven't seen that fail to work myself, and indeed I always keep a breakpoint on malloc_error_break set.
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:
string.Empty.PadRight(totalLength, (char)32);
An alternative approach: Create all spaces manually within a custom method and call it:
private static string GetSpaces(int totalLength)
{
string result = string.Empty;
for (int i = 0; i < totalLength; i++)
{
result += " ";
}
return result;
}
And call it in your code to create white spaces: GetSpaces(14);
in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.
The date function can return this if you specify the format correctly:
$daynum = date("w", strtotime("wednesday"));
will return 0 for Sunday through to 6 for Saturday.
An alternative format is:
$daynum = date("N", strtotime("wednesday"));
which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).
Well, you must first drop the auto_increment
and primary key
you have and then add yours, as follows:
-- drop auto_increment capability
alter table `users` modify column id INT NOT NULL;
-- in one line, drop primary key and rebuild one
alter table `users` drop primary key, add primary key(id);
-- re add the auto_increment capability, last value is remembered
alter table `users` modify column id INT NOT NULL AUTO_INCREMENT;
In your config file give the relative path
ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
Change the DataDirectory to your executable path
string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);
If you are using EntityFramework, then you can set the DataDirectory path in your Context class
There is another way to convert Python scripts to .exe files. You can compile Python programs into C++ programs, which can be natively compiled just like any other C++ program.
or Powershell for a 0 indexed array.
PS C:\> "AAA BBB CCC DDD EEE FFF".Split()
AAA
BBB
CCC
DDD
EEE
FFF
PS C:\> ("AAA BBB CCC DDD EEE FFF".Split())[0]
AAA
Our git repo disk is mounted on AIX box to do BUILD.
It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.
The build server should have its own copy of the git repository, and it will be locally managed by git
on the build server.
The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull
to update the local repository on the build server.
If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.
xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.
panel.setStyle("-fx-background-color: #FFFFFF;");
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
As a JavaScript MV* beginner and purely focusing on the application architecture (not the server/client-side matters), I would certainly recommend the following resource (which I am surprised wasn't mentioned yet): JavaScript Design Patterns, by Addy Osmani, as an introduction to different JavaScript Design Patterns. The terms used in this answer are taken from the linked document above. I'm not going to repeat what was worded really well in the accepted answer. Instead, this answer links back to the theoretical backgrounds which power AngularJS (and other libraries).
Like me, you will quickly realize that AngularJS (or Ember.js, Durandal, & other MV* frameworks for that matter) is one complex framework assembling many of the different JavaScript design patterns.
I found it easier also, to test (1) native JavaScript code and (2) smaller libraries for each one of these patterns separately before diving into one global framework. This allowed me to better understand which crucial issues a framework adresses (because you are personally faced with the problem).
For example:
NB: This list is not complete, nor 'the best libraries'; they just happen to be the libraries I used. These libraries also include more patterns, the ones mentioned are just their main focuses or original intents. If you feel something is missing from this list, please do mention it in the comments, and I will be glad to add it.
Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):
>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']
Check that you didn't overwrite list
by accident:
>>> assert list == __builtins__.list
Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta
Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.
The + $File.FullName
is optional, and shows how to put a variable into the string.
You can use COALESCE
in conjunction with NULLIF
for a short, efficient solution:
COALESCE( NULLIF(yourField,'') , '0' )
The NULLIF
function will return null if yourField
is equal to the second value (''
in the example), making the COALESCE
function fully working on all cases:
QUERY | RESULT
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null ,''),'0') | '0'
SELECT COALESCE(NULLIF('' ,''),'0') | '0'
SELECT COALESCE(NULLIF('foo' ,''),'0') | 'foo'
Code Behind:
public class Friends
{
public string ID { get; set; }
public string Name { get; set; }
public string Image { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List <Friends> friendsList = new List<Friends>();
foreach (var friend in friendz)
{
friendsList.Add(
new Friends { ID = friend.id, Name = friend.name }
);
}
this.rptFriends.DataSource = friendsList;
this.rptFriends.DataBind();
}
.aspx Page
<asp:Repeater ID="rptFriends" runat="server">
<HeaderTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ID") %></td>
<td><%# Eval("Name") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
Well, just to be different, I found an article that references using Reflection.Emit to do so.
Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.
You do not need {{}}
in when conditions. What you are searching for is:
- fail: msg="unsupported version"
when: version not in acceptable_versions
A 404 return code actually means 'resource not found', and applies to any entity for which a request was made but not satisfied. So it works equally-well for pages, subsections of pages, and any item that exists on the page which has a specific request to be rendered.
So 404 is the right code to use in this scenario. Note that it doesn't apply to 'server not found', which is a different situation in which a request was issued but not answered at all, as opposed to answered but without the resource requested.
Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.
try this:
private static java.sql.Date getCurrentDate(String date) {
java.util.Date today;
java.sql.Date rv = null;
try {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
today = format.parse(date);
rv = new java.sql.Date(today.getTime());
System.out.println(rv.getTime());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
return rv;
}
}
Will return a java.sql.Date object for setDate();
The function above will print out a long value:
1375934400000
This is a one line solution involving LINQ.
var elements = new String[] { "1", "2", "3" };
Foo(elements.Cast<object>().ToArray())
You can use this code on view.blade. {{var_dump($animales)}}
*/
import {Component,ViewChild} from '@angular/core' /*Import View Child*/
@Component({
selector:'display'
template:`
<input #myname (input) = "updateName(myname.value)"/>
<p> My name : {{myName}}</p>
`
})
export class DisplayComponent{
@ViewChild('myname')inputTxt:ElementRef; /*create a view child*/
myName: string;
updateName: Function;
constructor(){
this.myName = "Aman";
this.updateName = function(input: String){
this.inputTxt.nativeElement.value=this.myName;
/*assign to it the value*/
};
}
}
Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:
Avoid reloading activity with asynctask on orientation change in android
Add android:configChanges="keyboardHidden|orientation"
to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
See Developer reference configChanges for more details.
However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.
Update: As of Android 3.2, you also need to add "screenSize":
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
From Developer guide Handling the Configuration Change Yourself
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare
android:configChanges="orientation|screenSize"
. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
myInt.ToString("D4");
Yes, you understood correctly.
CountDownLatch
works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch
.
Any thread, usually the main thread of the application, which calls CountDownLatch.await()
will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown()
once they are completed or ready.
As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch
is that it's not reusable: once count reaches zero you cannot use CountDownLatch
any more.
Edit:
Use CountDownLatch
when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.
A classical example of using CountDownLatch
in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.
P.S. OP's question has a pretty straightforward example so I didn't include one.
I suppose your dictMap is of type HashMap
, which makes it default to HashMap<Object, Object>
. If you want it to be more specific, declare it as HashMap<String, ArrayList>
, or even better, as HashMap<String, ArrayList<T>>
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
For anyone else arriving at this question:
I was performing the most simple jQuery, trying to hide an element:
('#fileselection').hide();
and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'
Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:
$('#fileselection').hide();
This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!
It depends on what kind of markdown parser you're using. For example in showdownjs there is an option {simpleLineBreaks: true}
which gives corresponding html for the following md input:
a line
wrapped in two
<p>a line<br>
wrapped in two</p>
In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:
<fieldset class="border p-2">
<legend class="w-auto">Your Legend</legend>
</fieldset>
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
Open libraries/Input.php
(system/core/Input.php
in CI version 2.0+
) and locate function _clean_input_keys($str){
,
Modify if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
to if ( ! preg_match("/^[a-z0-9:_\-|]+$/i", $str))
You need #include<string>
to use string
AND #include<iostream>
to use cin
and cout
. (I didn't get it when I read the answers). Here's some code which works:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string name;
cin >> name;
string message("hi");
cout << name << message;
return 0;
}
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
@ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
@ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.
I got trouble to get it so I post pictures showing different options:
Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]
In tab Sources
:
When button is activated, you can Pause On Caught Exceptions
with the checkbox below:
Chrome 27.0.1453.93 Stable
The embed URL for a channel's live stream is:
https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID
You can find your CHANNEL_ID at https://www.youtube.com/account_advanced
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
What is namedtuple ?
As the name suggests, namedtuple is a tuple with name. In standard tuple, we access the elements using the index, whereas namedtuple allows user to define name for elements. This is very handy especially processing csv (comma separated value) files and working with complex and large dataset, where the code becomes messy with the use of indices (not so pythonic).
How to use them ?
>>>from collections import namedtuple
>>>saleRecord = namedtuple('saleRecord','shopId saleDate salesAmout totalCustomers')
>>>
>>>
>>>#Assign values to a named tuple
>>>shop11=saleRecord(11,'2015-01-01',2300,150)
>>>shop12=saleRecord(shopId=22,saleDate="2015-01-01",saleAmout=1512,totalCustomers=125)
Reading
>>>#Reading as a namedtuple
>>>print("Shop Id =",shop12.shopId)
12
>>>print("Sale Date=",shop12.saleDate)
2015-01-01
>>>print("Sales Amount =",shop12.salesAmount)
1512
>>>print("Total Customers =",shop12.totalCustomers)
125
Interesting Scenario in CSV Processing :
from csv import reader
from collections import namedtuple
saleRecord = namedtuple('saleRecord','shopId saleDate totalSales totalCustomers')
fileHandle = open("salesRecord.csv","r")
csvFieldsList=csv.reader(fileHandle)
for fieldsList in csvFieldsList:
shopRec = saleRecord._make(fieldsList)
overAllSales += shopRec.totalSales;
print("Total Sales of The Retail Chain =",overAllSales)
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data
that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
--logic FOR OVERLAPPING DATES
DECLARE @StartDate datetime --Reference start date
DECLARE @EndDate datetime --Reference end date
DECLARE @NewStartDate datetime --New Start date
DECLARE @NewEndDate datetime --New End Date
Select
(Case
when @StartDate is null
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate < @NewStartDate)
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate > @NewEndDate)
then @NewStartDate
when (@StartDate<@NewStartDate and @EndDate > @NewStartDate)
then @NewStartDate
when (@StartDate>@NewStartDate and @NewEndDate < @StartDate)
then @NewStartDate
else @StartDate end) as StartDate,
(Case
when @EndDate is null
then @NewEndDate
when (@EndDate>@NewEndDate and @Startdate < @NewEndDate)
then @NewEndDate
when (@EndDate>@NewEndDate and @Startdate > @NewEndDate)
then @NewEndDate
when (@EndDate<@NewEndDate and @NewStartDate > @EndDate)
then @NewEndDate
else @EndDate end) as EndDate