<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
The latest specification allows line feed character, so a simple line break inside the attribute or entity
(note that characters #
and ;
are required) are OK.
The code below works for me with Xcode 7:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Your Title"
}
The problem is that $title
is being referenced on line 5 before it's being assigned on line 58. Rearranging your code isn't easy, because the data is both retrieved and output at the same time. Just to test, how does something like this work?
Because you're only retrieving one row, you don't need to use a while loop, but I left it with hopes that it'll make it easier for you to relate to your current code. All I've done is removed the actual output from your data retrieval, and added variables for category and category name which are then referred to as usual later on. Also, I haven't tested this. :)
suptitle
seems the way to go, but for what it's worth, the figure
has a transFigure
property that you can use:
fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui
files.
Initially I tried to use ui->setWindowTitle
, but that doesn't exist. ui
is not a QDialog
or a QMainWindow
.
The owner of the ui
is the QDialog
or QMainWindow
, the .ui
just describes how to lay it out. In that case, you would use:
this->setWindowTitle("New Title");
I hope this helps someone else.
Java code:
write this in onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.action_bar);
and for you custom view, simply use FrameLayout, east peasy!
android.support.v7.widget.Toolbar is another option
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/app_name"
android:textColor="@color/black"
android:id="@+id/textView" />
</FrameLayout>
There's no need to use jQuery to change the title. Try:
document.title = "blarg";
See this question for more details.
To dynamically change on button click:
$(selectorForMyButton).click(function(){
document.title = "blarg";
});
To dynamically change in loop, try:
var counter = 0;
var titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
To string the two together so that it dynamically changes on button click, in a loop:
var counter = 0;
$(selectorForMyButton).click(function(){
titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
});
Take a peek in platforms/android-2.1/data/res/layout/screen.xml
of the SDK. It seems to define a title there. You can frequently examine layouts like this and borrow the
style="?android:attr/windowTitleStyle"
styles which you can then use and override in your own TextViews.
You may be able to even select the title for direct tweaking by doing:
TextView title = (TextView)findViewById(android.R.id.title);
It can also be done this way:
figure(xx);
set(gcf, 'name', 'Name goes here')
gcf
gets the current figure handle.
Put in the URL bar and then click enter:
javascript:alert(document.title);
You can select and copy the text from the alert depending on the website and the web browser you are using.
Php's native function: get_meta_tags()
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:
var fs = require('fs');
var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();
If you don't want to change the router, just go to the HomeController and change MyNewViewHere in the index like this:
public ActionResult Index()
{
return View("MyNewViewHere");
}
Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.
Seems like answered here: https://public-inbox.org/git/[email protected]/
So in a similar way, running
$ git diff --cc $M $M^1 $M^2 $(git merge-base $M^1 $M^2)
should show a combined patch that explains the state at $M relative to the states recorded in its parents and the merge base.
This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.
as a simple example:
CREATE DATABASE LINK _dblink_name_ CONNECT TO _username_ IDENTIFIED BY _passwd_ USING '$_ORACLE_SID_'
for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm
Make sure that you enabled anonymous authentication on iis like this:
You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.
In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).
If you suspect a memory leak, use a profiler to find which object occupies all the available memory.
The method you are looking for is .limit.
Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.
Example usage:
df.limit(1000)
Ion Todirel already mentioned an answer YES using std::reference_wrapper
. Since C++11 we have a mechanism to retrieve object from std::vector
and remove the reference by using std::remove_reference
. Below is given an example compiled using g++
and clang
with option
-std=c++11
and executed successfully.
#include <iostream>
#include <vector>
#include<functional>
class MyClass {
public:
void func() {
std::cout << "I am func \n";
}
MyClass(int y) : x(y) {}
int getval()
{
return x;
}
private:
int x;
};
int main() {
std::vector<std::reference_wrapper<MyClass>> vec;
MyClass obj1(2);
MyClass obj2(3);
MyClass& obj_ref1 = std::ref(obj1);
MyClass& obj_ref2 = obj2;
vec.push_back(obj_ref1);
vec.push_back(obj_ref2);
for (auto obj3 : vec)
{
std::remove_reference<MyClass&>::type(obj3).func();
std::cout << std::remove_reference<MyClass&>::type(obj3).getval() << "\n";
}
}
The text below comes from Comparator vs Comparable
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable
interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator
interface.
Fluid layout in Bootstrap 3.
Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.
container-fluid
is added back in Bootstrap 3.1
A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:
.container-fixed;
The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.
Another approach is to use Eric Flowers' CSS style
.my-fluid-container {
padding-left: 15px;
padding-right: 15px;
margin-left: auto;
margin-right: auto;
}
Looking at Ruby only:
TL;DR
Use none?
passing it a block with ==
for the comparison:
[1, 2].include?(1)
#=> true
[1, 2].none? { |n| 1 == n }
#=> false
Array#include?
accepts one argument and uses ==
to check against each element in the array:
player = [1, 2, 3]
player.include?(1)
#=> true
Enumerable#none?
can also accept one argument in which case it uses ===
for the comparison. To get the opposing behaviour to include?
we omit the parameter and pass it a block using ==
for the comparison.
player.none? { |n| 7 == n }
#=> true
!player.include?(7) #notice the '!'
#=> true
In the above example we can actually use:
player.none?(7)
#=> true
That's because Integer#==
and Integer#===
are equivalent. But consider:
player.include?(Integer)
#=> false
player.none?(Integer)
#=> false
none?
returns false
because Integer === 1 #=> true
. But really a legit notinclude?
method should return true
. So as we did before:
player.none? { |e| Integer == e }
#=> true
Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.
You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).
So, when you are pushing a commit, what git does it pushes a set of references like in this picture:
If you didn't push your master branch yet, the whole history of the branch will get pushed.
So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.
To do what you asked for, you need to create a clean branch with no history, like in this answer.
You Can also set the background color to Clear to achieve the same effect as UITableViewCellSelectionStyleNone
, in case you don't want to/ can't use UITableViewCellSelectionStyleNone
.
You would use code like the following:
UIView *backgroundColorView = [[UIView alloc] init];
backgroundColorView.backgroundColor = [UIColor clearColor];
backgroundColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView: backgroundColorView];
This may degrade your performance as your adding an extra colored view to each cell.
Duplicated id
for pairs name
and city
:
select s.id, t.*
from [stuff] s
join (
select name, city, count(*) as qty
from [stuff]
group by name, city
having count(*) > 1
) t on s.name = t.name and s.city = t.city
Thanks a bundle, guys. You are great.
I used Chuff's answer and modified it a little to do what I wanted.
I have 2 worksheets in the same workbook.
On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message
Then I inserted a new blank column next to the phone number
On worksheet 2 I have two columns: phone number, name of person
Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.
Then just copy the formula down the whole column until last sms It worked beautifully.
=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)
Try this :
var results= persons.GroupBy(n => n.PersonId)
.Select(g => new {
PersonId=g.Key,
Cars=g.Select(p=>p.car).ToList())}).ToList();
But performance-wise the following practice is better and more optimized in memory usage (when our array contains much more items like millions):
var carDic=new Dictionary<int,List<string>>();
for(int i=0;i<persons.length;i++)
{
var person=persons[i];
if(carDic.ContainsKey(person.PersonId))
{
carDic[person.PersonId].Add(person.car);
}
else
{
carDic[person.PersonId]=new List<string>(){person.car};
}
}
//returns the list of cars for PersonId 1
var carList=carDic[1];
This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.
ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
DECLARE @bit INT,
@field INT,
@maxfield INT,
@char INT,
@fieldname VARCHAR(128),
@TableName VARCHAR(128),
@PKCols VARCHAR(1000),
@sql VARCHAR(2000),
@UpdateDate VARCHAR(21),
@UserName VARCHAR(128),
@Type CHAR(1),
@PKSelect VARCHAR(1000)
--You will need to change @TableName to match the table to be audited.
-- Here we made GUESTS for your example.
SELECT @TableName = 'PERSON'
SELECT @UserName = SYSTEM_USER,
@UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)
-- Action
IF EXISTS (
SELECT *
FROM INSERTED
)
IF EXISTS (
SELECT *
FROM DELETED
)
SELECT @Type = 'U'
ELSE
SELECT @Type = 'I'
ELSE
SELECT @Type = 'D'
-- get list of columns
SELECT * INTO #ins
FROM INSERTED
SELECT * INTO #del
FROM DELETED
-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on')
+ ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect + '+', '')
+ '''<[' + COLUMN_NAME
+ ']=''+convert(varchar(100),
coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF @PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, @TableName)
RETURN
END
SELECT @field = 0,
-- @maxfield = MAX(COLUMN_NAME)
@maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
MAX(
COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
)
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
SELECT @field = MIN(
COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
)
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
) > @field
SELECT @bit = (@field - 1)% 8 + 1
SELECT @bit = POWER(2, @bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
OR @Type IN ('I', 'D')
BEGIN
SELECT @fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
) = @field
SELECT @sql =
'
insert into Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + @Type + ''','''
+ @TableName + ''',' + @PKSelect
+ ',''' + @fieldname + ''''
+ ',convert(varchar(1000),d.' + @fieldname + ')'
+ ',convert(varchar(1000),i.' + @fieldname + ')'
+ ',''' + @UpdateDate + ''''
+ ',''' + @UserName + ''''
+ ' from #ins i full outer join #del d'
+ @PKCols
+ ' where i.' + @fieldname + ' <> d.' + @fieldname
+ ' or (i.' + @fieldname + ' is null and d.'
+ @fieldname
+ ' is not null)'
+ ' or (i.' + @fieldname + ' is not null and d.'
+ @fieldname
+ ' is null)'
EXEC (@sql)
END
END
This works:
<div id="start-element">Click Me</div>
$(document).on("click","#test-element",function() {
alert("click");
});
$(document).on("click","#start-element",function() {
$(this).attr("id", "test-element");
});
Here is the Fiddle
For me, the only thing which worked is
git diff HEAD
including the staged files, git diff --cached
only shows staged files.
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
If you use gcc, there's gprof available.
I wanted to the know how programmer find memory leak
Some uses tools, some does what you do, could also through peer code review
Is there any standard or procedure one should follow to ensure there is no memory leak in the program
For me: whenever I create dynamically allocated objects, I always put the freeing code after, then fill the code between. This would be OK if you're sure there won't be exceptions in the code between. Otherwise, I make use of try-finally (I don't use C++ frequently).
Relative paths are relative to current working directory. If you do not your want your path to be, it must be absolute.
But there is an often used trick to build an absolute path from current script: use its __file__
special attribute:
from pathlib import Path
path = Path(__file__).parent / "../data/test.csv"
with path.open() as f:
test = list(csv.reader(f))
This requires python 3.4+ (for the pathlib module).
If you still need to support older versions, you can get the same result with:
import csv
import os.path
my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../data/test.csv")
with open(path) as f:
test = list(csv.reader(f))
[2020 edit: python3.4+ should now be the norm, so I moved the pathlib version inspired by jpyams' comment first]
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
Basically ng-click
first checks the isDisabled
and based on its value it will decide whether the function should be called or not.
<span ng-click="(isDisabled) || clicked()">Do something</span>
OR read it as
<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>
HTML Table row heights will typically change proportionally to the table height, if the table height is larger than the height of your rows. Since the table is forcing the height of your rows, you can remove the table height to resolve the issue. If this is not acceptable, you can also give the rows explicit height, and add a third row that will auto size to the remaining table height.
Another option in CSS2 is the Max-Height Property, although it may lead to strange behavior in a table.http://www.w3schools.com/cssref/pr_dim_max-height.asp
.
I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array
instead of !empty
. If $items
happens to be a nonzero scalar, then the foreach
will still error out if you use !empty
.
You can do it like this
mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist) # prints: ['d', 'c', 'a', 'b', 'e']
Use active class with label to make it auto select and use checked=""
.
<label class="btn btn-primary active" value="regular" style="width:47%">
<input type="radio" name="service" checked="" > Regular </label>
<label class="btn btn-primary " value="express" style="width:46%">
<input type="radio" name="service"> Express </label>
I am doing this way:
<div class="card-logo">
<img height="100%" width="100%" src="http://someimage.jpg">
</div>
and CSS:
.card-logo {
width: 20%;
}
I prefer this way, as if I need to upscale - I can use 150% as well
def get_clients():
first_run = True
startMainMenu = False
while True:
if first_run:
global done
done = False
Thread(target=animate, args=("Waiting For Connection",)).start()
Client, address = objSocket.accept()
global menuIsOn
if menuIsOn:
menuIsOn = False # will stop main menu
startMainMenu = True
done = True
# Get Current Directory in Client Machine
current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")
# beep on connection
beep()
print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
print('* Connected to: ' + address[0] + ':' + str(address[1]))
try:
get_client_info(Client, first_run)
except Exception as e:
print("Error data received is not a json!")
print(e)
now = datetime.now()
current_time = now.strftime("%D %H:%M:%S")
print("* Current Time =", current_time)
print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)
connections.append(Client)
addresses.append(address)
if first_run:
Thread(target=threaded_main_menu, daemon=True).start()
first_run = False
else:
print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
if startMainMenu == True:
Thread(target=threaded_main_menu, daemon=True).start()
startMainMenu = False
This is a nice tutorial:
http://android-developers.blogspot.de/2009/05/painless-threading.html
Or this for the UI thread:
http://developer.android.com/guide/faq/commontasks.html#threading
Or here a very practical one:
http://www.androidacademy.com/1-tutorials/43-hands-on/115-threading-with-android-part1
and another one about procceses and threads
http://developer.android.com/guide/components/processes-and-threads.html
You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:
NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")
The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:
# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd
# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41
# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41
# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41
As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.
I was unable to find a solution that was neatly portable between Mac OS Catalina, Ubuntu 16 and Centos 7, so I decided to do it with python inline and it worked well for my bash scripts.
to_abs_path() {
python -c "import os; print os.path.abspath('$1')"
}
to_abs_path "/some_path/../secrets"
From Bitbucket:
Push up an existing repository. You already have a Git repository on your computer. Let's push it up to Bitbucket:
cd /path/to/my/repo
git remote add origin ssh://[email protected]/javacat/geo.git
git push -u origin --all # To push up the repo for the first time
Make sure you have a service started and listening on the port.
netstat -ln | grep 8080
and
sudo netstat -tulpn
Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.
If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.
You can try for example RANDOM.ORG (it reduces performance)
As others have said you are "tainting" the canvas by loading from a cross origins domain.
https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
However, you may be able to prevent this by simply setting:
img.crossOrigin = "Anonymous";
This only works if the remote server sets the following header appropriately:
Access-Control-Allow-Origin "*"
The Dropbox file chooser when using the "direct link" option is a great example of this. I use it on oddprints.com to hoover up images from the remote dropbox image url, into my canvas, and then submit the image data back into my server. All in javascript
You can choose any extension in the world if you setup Apache correctly. You could use .html to do PHP if you set up in your Apache config.
In conclusion, extension has nothing to do with the app or website itself. You can use the one you want, but normaly, use .php (to not reinvent the wheel)
But in 2019, you should use routing and forgot about extension at the end.
I recommend you using Laravel.
In answer to @KingCrunch: True, Apache not use it by default but you can easily use it if you change config. But this it not recommended since everybody know that it not really an option.
I already saw .html files that executed PHP using the html extension.
Even I had same problem, The reason was mysql service was not getting configured properly, when I installed it through 'MySQL installer'. Also it was not starting, when I tried to start the service manually.
So in my case it seemed be a Bug with the 'MySQL Installer', as editing the install path to a different one when the 'Developer default' was selected, the problem occurs.
Solution (Not exactly a solution):
File.Create
returns a FileStream
object that you can call Close()
on.
Adding this in the config.inc.php
file worked for me (under the last $cfg line):
$cfg['RowActionLinksWithoutUnique'] = 'true';
The file should be located in the phpMyAdmin
folder on your local computer
Try this code it works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
MsgBox(CustomeDate.ToString)
con.Open()
dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)
ds = New System.Data.DataSet
dadap.Fill(ds)
Dgview.DataSource = ds.Tables(0)
con.Close()
Note : if u use dd
for date representation it will return nothing while selecting 1 to 9 so use d
for selection
'Date time format
'MMM Three-letter month.
'ddd Three-letter day of the week.
'd Day of the month.
'HH Two-digit hours on 24-hour scale.
'mm Two-digit minutes.
'yyyy Four-digit year.
The documentation contains a full list of the date formats.
I strongly recommend using Joda Time http://joda-time.sourceforge.net/faq.html
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
Short answer: Command >filename 2>&1
or Command &>filename
Explanation:
Consider the following code which prints the word "stdout" to stdout and the word "stderror" to stderror.
$ (echo "stdout"; echo "stderror" >&2)
stdout
stderror
Note that the '&' operator tells bash that 2 is a file descriptor (which points to the stderr) and not a file name. If we left out the '&', this command would print stdout
to stdout, and create a file named "2" and write stderror
there.
By experimenting with the code above, you can see for yourself exactly how redirection operators work. For instance, by changing which file which of the two descriptors 1,2
, is redirected to /dev/null
the following two lines of code delete everything from the stdout, and everything from stderror respectively (printing what remains).
$ (echo "stdout"; echo "stderror" >&2) 1>/dev/null
stderror
$ (echo "stdout"; echo "stderror" >&2) 2>/dev/null
stdout
Now, we can explain why the solution why the following code produces no output:
(echo "stdout"; echo "stderror" >&2) >/dev/null 2>&1
To truly understand this, I highly recommend you read this webpage on file descriptor tables. Assuming you have done that reading, we can proceed. Note that Bash processes left to right; thus Bash sees >/dev/null
first (which is the same as 1>/dev/null
), and sets the file descriptor 1 to point to /dev/null instead of the stdout. Having done this, Bash then moves rightwards and sees 2>&1
. This sets the file descriptor 2 to point to the same file as file descriptor 1 (and not to file descriptor 1 itself!!!! (see this resource on pointers for more info)) . Since file descriptor 1 points to /dev/null, and file descriptor 2 points to the same file as file descriptor 1, file descriptor 2 now also points to /dev/null. Thus both file descriptors point to /dev/null, and this is why no output is rendered.
To test if you really understand the concept, try to guess the output when we switch the redirection order:
(echo "stdout"; echo "stderror" >&2) 2>&1 >/dev/null
stderror
The reasoning here is that evaluating from left to right, Bash sees 2>&1, and thus sets the file descriptor 2 to point to the same place as file descriptor 1, ie stdout. It then sets file descriptor 1 (remember that >/dev/null = 1>/dev/null) to point to >/dev/null, thus deleting everything which would usually be send to to the standard out. Thus all we are left with was that which was not send to stdout in the subshell (the code in the parentheses)- i.e. "stderror".
The interesting thing to note there is that even though 1 is just a pointer to the stdout, redirecting pointer 2 to 1 via 2>&1
does NOT form a chain of pointers 2 -> 1 -> stdout. If it did, as a result of redirecting 1 to /dev/null, the code 2>&1 >/dev/null
would give the pointer chain 2 -> 1 -> /dev/null, and thus the code would generate nothing, in contrast to what we saw above.
Finally, I'd note that there is a simpler way to do this:
From section 3.6.4 here, we see that we can use the operator &>
to redirect both stdout and stderr. Thus, to redirect both the stderr and stdout output of any command to \dev\null
(which deletes the output), we simply type
$ command &> /dev/null
or in case of my example:
$ (echo "stdout"; echo "stderror" >&2) &>/dev/null
Key takeaways:
2>&1 >/dev/null
is != >/dev/null 2>&1
. One generates output and the other does not!Finally have a look at these great resources:
Bash Documentation on Redirection, An Explanation of File Descriptor Tables, Introduction to Pointers
If the question is about counting the number of keywords then would recommend something like
def countoccurrences(store, value):
try:
store[value] = store[value] + 1
except KeyError as e:
store[value] = 1
return
in the main function have something that loops through the data and pass the values to countoccurrences function
if __name__ == "__main__":
store = {}
list = ('a', 'a', 'b', 'c', 'c')
for data in list:
countoccurrences(store, data)
for k, v in store.iteritems():
print "Key " + k + " has occurred " + str(v) + " times"
The code outputs
Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times
Try using:
string ap = c.Request["AP"];
That reads from the cookies, form, query string or server variables.
Alternatively:
string ap = c.Request.Form["AP"];
to just read from the form's data.
Based on the code I've used for finding multiple instances of a string within a larger string, your code would look like:
List<int> inst = new List<int>();
int index = 0;
while (index >=0)
{
index = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index);
inst.Add(index);
index++;
}
String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
happy coding!
Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example
@Ethan's answer would completely work. From my experience, the more node way is to use environment variables. It's a standard way to configure programs deployed on hosting platforms (e.g. Heroku or Dokku).
To pass the parameter from the command line, do it like this:
Development:
gulp dev
Production:
NODE_ENV=production gulp dev
The syntax is different, but very Unix, and it's compatible with Heroku, Dokku, etc.
You can access the variable in your code at process.env.NODE_ENV
MYAPP=something_else gulp dev
would set
process.env.MYAPP === 'something_else'
This answer might give you some other ideas.
If you're using Java 8 and you're willing to write a few reusable methods, you can do it in one line.
private Map<String, List<String>> parse(final String query) {
return Arrays.asList(query.split("&")).stream().map(p -> p.split("=")).collect(Collectors.toMap(s -> decode(index(s, 0)), s -> Arrays.asList(decode(index(s, 1))), this::mergeLists));
}
private <T> List<T> mergeLists(final List<T> l1, final List<T> l2) {
List<T> list = new ArrayList<>();
list.addAll(l1);
list.addAll(l2);
return list;
}
private static <T> T index(final T[] array, final int index) {
return index >= array.length ? null : array[index];
}
private static String decode(final String encoded) {
try {
return encoded == null ? null : URLDecoder.decode(encoded, "UTF-8");
} catch(final UnsupportedEncodingException e) {
throw new RuntimeException("Impossible: UTF-8 is a required encoding", e);
}
}
But that's a pretty brutal line.
I used a modified version of this answer - based on my experiences adding it to VS 2010:
Tools
>> External Tools
in Visual StudioAdd
Visual Studio Command &Prompt
&P
Makes P a alt-shortcut key (when menu active)C:\Windows\System32\cmd.exe
\k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsvars32.bat
/k
keeps a secondary session active so the window doesn’t close on the .bat file$(ProjectDir)
(from the dropdown)Now you have command prompt access under the Tools Menu.
Note: this solution will work with WebClientSocket as well as with HttpWebRequest or any other class that uses WebHeaderCollection to work with headers.
If you look at the source code of WebHeaderCollection.cs you will see that Hinfo is used to keep information of all known headers:
private static readonly HeaderInfoTable HInfo = new HeaderInfoTable();
Looking at HeaderInfoTable class, you can notice all the data is stored into hash table
private static Hashtable HeaderHashTable;
Further, in static contructor of HeaderInfoTable, you can see all known headers are added in HeaderInfo array and then copied into hashtable.
Final look at HeaderInfo class shows the names of the fields.
internal class HeaderInfo {
internal readonly bool IsRequestRestricted;
internal readonly bool IsResponseRestricted;
internal readonly HeaderParser Parser;
//
// Note that the HeaderName field is not always valid, and should not
// be used after initialization. In particular, the HeaderInfo returned
// for an unknown header will not have the correct header name.
//
internal readonly string HeaderName;
internal readonly bool AllowMultiValues;
...
}
So, with all the above, here is a code that uses reflection to find static Hashtable in HeaderInfoTable class and then changes every request-restricted HeaderInfo inside hash table to be unrestricted
// use reflection to remove IsRequestRestricted from headerInfo hash table
Assembly a = typeof(HttpWebRequest).Assembly;
foreach (FieldInfo f in a.GetType("System.Net.HeaderInfoTable").GetFields(BindingFlags.NonPublic | BindingFlags.Static))
{
if (f.Name == "HeaderHashTable")
{
Hashtable hashTable = f.GetValue(null) as Hashtable;
foreach (string sKey in hashTable.Keys)
{
object headerInfo = hashTable[sKey];
//Console.WriteLine(String.Format("{0}: {1}", sKey, hashTable[sKey]));
foreach (FieldInfo g in a.GetType("System.Net.HeaderInfo").GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
if (g.Name == "IsRequestRestricted")
{
bool b = (bool)g.GetValue(headerInfo);
if (b)
{
g.SetValue(headerInfo, false);
Console.WriteLine(sKey + "." + g.Name + " changed to false");
}
}
}
}
}
}
Working solution is by using in-build: panelClass attribute and set styles in global style.css (with !important):
https://material.angular.io/components/select/api
/* style.css */
.matRole .mat-option-text {
height: 4em !important;
}
_x000D_
<mat-select panelClass="matRole">...
_x000D_
Summary: to get physical CPUs do this:
grep 'core id' /proc/cpuinfo | sort -u
to get physical and logical CPUs do this:
grep -c ^processor /proc/cpuinfo
/proc
<< this is the golden source of any info you need about processes and
/proc/cpuinfo
<< is the golden source of any CPU information.
Dropping the postgres
database doesn't really matter. This database is initially empty and its purpose is simply for the postgres
user to have a kind of "home" to connect to, should it need one.
Still you may recreate it with the SQL command CREATE DATABASE postgres;
Note that the tutorial mentioned in the question is not written with postgres.app
in mind.
Contrary to PostgreSQL for Unix in general, postgres.app
tries to look like a normal application as opposed to a service that would be run by a dedicated postgres
user having different privileges than your normal user. postgres.app
is run and managed by your own account.
So instead of this command: sudo -u postgres psql -U postgres
, it would be more in the spirit of postgres.app to just issue: psql
, which automatically connects to a database matching your users's name, and with a db account of the same name that happens to be superuser, so it can do anything permissions-wise.
export PATH=$PATH:/usr/local/git/bin:/usr/local/bin
One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH
should be double-quoted as "$PATH"
.
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
Step1: git rebase -i HEAD~n
to do interactive rebase for the last n
commits affected. (i.e. if you want to change a commit message 3 commits back, do git rebase -i HEAD~3
)
git will pop up an editor to handle those commits, notice this command:
# r, reword = use commit, but edit the commit message
that is exactly we need!
Step2: Change pick
to r
for those commits that you want to update the message. Don't bother changing the commit message here, it will be ignored. You'll do that on the next step. Save and close the editor.
Note that if you edit your rebase 'plan' yet it doesn't begin the process of letting you rename the files, run:
git rebase --continue
If you want to change the text editor used for the interactive session (e.g. from the default vi to nano), run:
GIT_EDITOR=nano git rebase -i HEAD~n
Step3: Git will pop up another editor for every revision you put r
before. Update the commit msg as you like, then save and close the editor.
Step4: After all commits msgs are updated. you might want to do git push -f
to update the remote.
You just need to:
Step 1: Go home directory of C:\ with typing cd.. (2 times)
Step 2: It appears now C:\>
Step 3: Type dir Windows\System32\run
That's all, it shows complete files & folder details inside target folder.
Details: I used Windows\System32\com
folder as example, you should type your own folder name etc. Windows\System32\run
There's a ES6 shorthand import, you can reference. More readable and easy to type.
import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';
class ExampleComponent extends Component {
static propTypes = {
annotationRanges: arrayOf(shape({
start: number,
end: number,
})).isRequired,
}
static defaultProps = {
annotationRanges: [],
}
}
The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.
Whenever I have to do string manipulations in C#, I miss the good old Left
and Right
functions from Visual Basic, which are much simpler to use than Substring
.
So in most of my C# projects, I create extension methods for them:
public static class StringExtensions
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
return str.Substring(str.Length - Math.Min(length, str.Length));
}
}
Note:
The Math.Min
part is there because Substring
throws an ArgumentOutOfRangeException
when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.
string longString = "Long String";
// returns "Long";
string left1 = longString.Left(4);
// returns "Long String";
string left2 = longString.Left(100);
As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.
I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As Variant
Dim objNode As Variant
Set objXML = CreateObject("MSXML2.DOMDocument")
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
When using -c
command, as a tricky way, instead of reading the stdin
(and more flexible in some cases) you can pass a shell script command as well to your python command by putting the shell command in quotes within a parenthesis started by $
sign.
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
This will count the number of lines from goldendict's history file.
This should work.
string temp = mystring.Replace("\n", "");
Are you sure there are actual \n new lines in your original string?
(Update September 2012):
MRT points out in the comments that "Eclipse Version" question references a .eclipseproduct
in the main folder, and it contains:
name=Eclipse Platform
id=org.eclipse.platform
version=3.x.0
So that seems more straightforward than my original answer below.
Also, Neeme Praks mentions below that there is a eclipse/configuration/config.ini
which includes a line like:
eclipse.buildId=4.4.1.M20140925-0400
Again easier to find, as those are Java properties set and found with System.getProperty("eclipse.buildId")
.
Original answer (April 2009)
For Eclipse Helios 3.6, you can deduce the Eclipse Platform version directly from the About screen:
It is a combination of the Eclipse global version and the build Id:
Here is an example for Eclipse 3.6M6:
The version would be: 3.6.0.v201003121448, after the version 3.6.0 and the build Id I20100312-1448 (an Integration build from March 12th, 2010 at 14h48
To see it more easily, click on "Plugin Details" and sort by Version.
Note: Eclipse3.6 has a brand new cool logo:
And you can see the build Id now being displayed during the loading step of the different plugin.
The Margin
property returns a Thickness
structure, of which Left
is a property. What the statement does is copying the structure value from the Margin
property and setting the Left
property value on the copy. You get an error because the value that you set will not be stored back into the Margin
property.
(Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...)
To set the property you would need to get the Thickness
structure from the Margin
property, set the value and store it back:
Thickness m = MyControl.Margin;
m.Left = 10;
MyControl.Margin = m;
If you are going to set all the margins, just create a Thickness
structure and set them all at once:
MyControl.Margin = new Thickness(10, 10, 10, 10);
I had a similar situation trying to exec()
a backend command and also getting no tty present and no askpass program specified
in the web server error log. Original (bad) code:
$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);
A bash
wrapper solved this issue, such as:
$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);
Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command
portion.
Having hit this one a few times and followed a bunch of suggestions, if you don't find it available after installing the NuGet Microsoft.AspNet.WebApi.Client manually add a reference from the packages folder in the solution to:
\Microsoft.AspNet.WebApi.Client.5.2.6\lib\net45\System.Net.Http.Formatting.dll
And don't get into the trap of adding older references to the System.Net.Http.Formatting.dll NuGet
Javascript version of the original function
/**
* Get a center latitude,longitude from an array of like geopoints
*
* @param array data 2 dimensional array of latitudes and longitudes
* For Example:
* $data = array
* (
* 0 = > array(45.849382, 76.322333),
* 1 = > array(45.843543, 75.324143),
* 2 = > array(45.765744, 76.543223),
* 3 = > array(45.784234, 74.542335)
* );
*/
function GetCenterFromDegrees(data)
{
if (!(data.length > 0)){
return false;
}
var num_coords = data.length;
var X = 0.0;
var Y = 0.0;
var Z = 0.0;
for(i = 0; i < data.length; i++){
var lat = data[i][0] * Math.PI / 180;
var lon = data[i][1] * Math.PI / 180;
var a = Math.cos(lat) * Math.cos(lon);
var b = Math.cos(lat) * Math.sin(lon);
var c = Math.sin(lat);
X += a;
Y += b;
Z += c;
}
X /= num_coords;
Y /= num_coords;
Z /= num_coords;
var lon = Math.atan2(Y, X);
var hyp = Math.sqrt(X * X + Y * Y);
var lat = Math.atan2(Z, hyp);
var newX = (lat * 180 / Math.PI);
var newY = (lon * 180 / Math.PI);
return new Array(newX, newY);
}
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
If you haven't found out yet, you can use the amazing screen plugin.
Conque is also exceptional but I find screen much more practical (it wont "litter" your buffer for example and you can just send the commands that you really want after editing them in your buffer)
This works for me:
git grep '<<<<<<< HEAD'
or
git grep '<<<<<<< HEAD' | less -N
I had a navigation controllers integrated in a TabbarController. This worked
self.navigationItem.title=@"title";
This happened to me when:
And the form method="POST"
I tried to access the action using the URL directly, without using the form submitt. Since the default method for the URL is the doGet method, when you don't use the form submit, you'll see @ your console the http 405 error.
Solution: Use only the form button you mapped to your servlet action.
If you have simple flavors (free/pro, demo/full etc.) then add to build.gradle file:
android {
...
flavorDimensions "version"
productFlavors {
free{
dimension "version"
...
}
pro{
dimension "version"
...
}
}
By dimensions you can create "flavors in flavors". Read more.
XSD (XML schema definition) defines the element in an XML document. It can be used to verify if the elements in the xml document adheres to the description in which the content is to be placed. While wsdl is specific type of XML document which describes the web service. WSDL itself adheres to a XSD.
For your requirement, Popen function of subprocess python module is the answer. For example,
import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
Select call is a way of having more precision (sleep time can be specified in nanoseconds).
lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);
And in your cancel method:
lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");
And in your update method:
lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;
I think you could experiment with different activity flags, as it sounds like multiple instances.
"singleTop" "singleTask" "singleInstance"
Are the ones I would try, they can be defined inside the manifest.
http://developer.android.com/guide/topics/manifest/activity-element.html
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.
CAUTION:
The begin <code> end while <condition>
is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop
, e.g.
loop do
# some code here
break if <condition>
end
Here's an email exchange in 23 Nov 2005 where Matz states:
|> Don't use it please. I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised. What do you regret about it?
Because it's hard for users to tell
begin <code> end while <cond>
works differently from
<code> while <cond>
RosettaCode wiki has a similar story:
During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.
To identify unlock screen I believe that you can use ID 4624. But then you also need to look at the Logon Type which in this case is 7: http://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4624
Event ID for Logoff is 4634
I had the same issue when I've modified .project xml-file. When I reverted files to original version the project was created, then I was able to import project. Maybe it helps someone who has the same kind of problem ;)
None of the answers work for me since I have many shared preferences keys.
Let's say you are running an Android Test instead of a unit test.
It is working for me loop and delete through all the shared_prefs files.
@BeforeClass will run before all the tests and ActivityTestRule
@BeforeClass
public static void setUp() {
Context context = InstrumentationRegistry.getTargetContext();
File root = context.getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}
}
Worked for me
var myForm = document.getElementById("form");
var formData = new FormData(myForm),
obj = {};
for (var entry of formData.entries()){
obj[entry[0]] = entry[1];
}
console.log(obj);
It means you're in "record macro" mode. This mode is entered by typing q
followed by a register name, and can be exited by typing q
again.
You can use a pseudo element to create the overlay.
.testclass {
background-image: url("../img/img.jpg");
position: relative;
}
.testclass:before {
content: "";
position: absolute;
left: 0; right: 0;
top: 0; bottom: 0;
background: rgba(0,0,0,.5);
}
If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as
module Mods
def self.foo
puts "Mods.foo(self)"
end
end
The module_function approach below will avoid breaking any classes which include all of Mods.
module Mods
def foo
puts "Mods.foo"
end
end
class Includer
include Mods
end
Includer.new.foo
Mods.module_eval do
module_function(:foo)
public :foo
end
Includer.new.foo # this would break without public :foo above
class Thing
def bar
Mods.foo
end
end
Thing.new.bar
However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?
Edited to show that includes still work if public :foo
is called after module_function :foo
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
days = days-366;
number_of_long_years++;
} else {
days=days-365;
}
year++;
}
can you try this way??
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
var joinedString= string.Join(";", myDict.Select(x => x.Key + "=" + x.Value));
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code
scGetruntotals.CommandTimeout = 180;
Note : the parameter value is in seconds.
use these settings with oauth2 in Postman:
Access Token URL = https://accounts.google.com/o/oauth2/token
SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema
{
"fields": [
{
"fieldName": "role",
"fieldType": "STRING",
"multiValued": true,
"readAccessType": "ADMINS_AND_SELF"
}
],
"schemaName": "SAML"
}
SCOPE = https://www.googleapis.com/auth/admin.directory.user
PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]
{
"customSchemas": {
"SAML": {
"role": [
{
"value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
"customType": "Admin"
}
]
}
}
}
As a bare minimum:
tsconfig:
"lib": [
"es2015"
]
and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel
object( your action method parameter), using MVC model binding feature.
You can validate your form at client side and if everything is fine, send the data to server. The valid()
method will come in handy.
$(function () {
$("#yourSubmitButtonID").click(function (e) {
e.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var isvalid = _form .valid(); // Tells whether the form is valid
if (isvalid)
{
$.post(_form.attr("action"), _form.serialize(), function (data) {
//check the result and do whatever you want
})
}
});
});
code example below:
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);
I always prefer let
to an instance variable for a couple of reasons:
nil
, which can lead to subtle bugs and false positives. Since let
creates a method, you'll get a NameError
when you misspell it, which I find preferable. It makes it easier to refactor specs, too.before(:each)
hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let
, the initialization code only runs if the example calls it.@
).let
and keeping my it
block nice and short.A related link can be found here: http://www.betterspecs.org/#let
HTML
<h1>
<span>
inline text<br>
background padding<br>
with box-shadow
</span>
</h1>
Css
h1{
font-size: 50px;
padding: 13px; //Padding on the sides so as not to stick.
span {
background: #111; // background color
color: #fff;
line-height: 1.3; //The height of indents between lines.
box-shadow: 13px 0 0 #111, -13px 0 0 #111; // Indents for each line on the sides.
}
}
From the documentation:
get cookie from response
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
{'example_cookie_name': 'example_cookie_value'}
give cookie back to server on subsequent request
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
SELECT MAX(id) FROM TABELNAME
This identifies the largest id and returns the value
/n
and /r
usage depends on the platform (Window, Mac, Linux) which you are using.
But there are some platform independent separators too:
System.lineSeparator()
System.getProperty("line.separator")
Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,
In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter
command.
x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]
# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
cols=[]
for l in lst:
if l=='A':
cols.append('red')
elif l=='B':
cols.append('blue')
else:
cols.append('green')
return cols
# Create the colors list using the function above
cols=pltcolor(x)
plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()
I set the column widths in the HTML markup like so:
<thead>
<tr>
<th style='width: 5%;'>ProjectId</th>
<th style='width: 15%;'>Title</th>
<th style='width: 40%;'>Abstract</th>
<th style='width: 20%;'>Keywords</th>
<th style='width: 10%;'>PaperName</th>
<th style='width: 10%;'>PaperURL</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="@item.ID">
<td>@item.ProjectId</td>
<td>@item.Title</td>
<td>@item.Abstract</td>
<td>@item.Keywords</td>
<td>@item.PaperName</td>
<td>@item.PaperURL</td>
</tr>
}
</tbody>
</table>
xgboost-0.6-cp36-cp36m-win_amd64.whl
for anaconda 3 (python 3.6)C:\
cd C:\
pip install C:\xgboost-0.6-cp36-cp36m-win_amd64.whl
conda update scikit-learn
Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items
:
>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False
That's because dict.items
returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable
How about something like:
\documentclass{article}
\usepackage{amssymb,amsmath}
\begin{document}
\begin{equation}\label{A_Label}
\begin{split}
w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
\end{split}
\end{equation}
\end{document}
which produces:
andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.
I wrote an in-depth blog post about this that you can check out here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
If the datepicker is in a row of a grid, try something like
editoptions : {
dataInit : function (e) {
$(e).datepicker({
onSelect : function (ev) {
// here your code
}
});
}
}
As in this forum post by Gonzalo Medina, a third way may be:
\documentclass{article}
\usepackage{caption}
\DeclareCaptionType{equ}[][]
%\captionsetup[equ]{labelformat=empty}
\begin{document}
Some text
\begin{equ}[!ht]
\begin{equation}
a=b+c
\end{equation}
\caption{Caption of the equation}
\end{equ}
Some other text
\end{document}
More details of the commands used from package caption
: here.
A screenshot of the output of the above code:
I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.
String path="/tmp";
String[] dirListing = null;
File dir = new File(path);
dirListing = dir.list();
Arrays.sort(dirListing);
System.out.println(Arrays.deepToString(dirListing));
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
Add This Code on Form Close Event whether you add new record or delete, it will recreate the Primary Keys from 1 to Last record.This code will not disturb other columns of table.
Sub updatePrimaryKeysOnFormClose()
Dim i, rcount As Integer
'Declare some object variables
Dim dbLib As Database
Dim rsTable1 As Recordset
'Set dbLib to the current database (i.e. LIBRARY)
Set dbLib = CurrentDb
'Open a recordset object for the Table1 table
Set rsTable1 = dbLib.OpenRecordset("Table1")
rcount = rsTable1.RecordCount
'== Add New Record ============================
For i = 1 To rcount
With rsTable1
rsTable1.Edit
rsTable1.Fields(0) = i
rsTable1.Update
'-- Go to Next Record ---
rsTable1.MoveNext
End With
Next
Set rsTable1 = rsTable1
End Sub
Java has a LinkedList implementation, that you might wanna check out. You can download the JDK and it's sources at java.sun.com.
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
<option value=''>- Please choose -</option>_x000D_
<option value='1'>1</option>_x000D_
<option value='2'>2</option>_x000D_
<option value='selectedvalue'>There we go!</option>_x000D_
<option value='3'>3</option>_x000D_
<option value='4'>4</option>_x000D_
<option value='5'>5</option>_x000D_
</select>
_x000D_
Okay, here's all of your bounty requirements met:
Here's a demo and link to my code (JSFiddle)
Here are the features that I've incorporated into this purely JS, CSS and HTML5 fiddle:
HTML:
<div id="wrapper">
<div id="a">Hover over this div to see a cool tool tip!</div>
</div>
CSS:
#a{
background-color:yellow;
padding:10px;
border:2px solid red;
}
.tooltip{
background:black;
color:white;
padding:5px;
box-shadow:0 0 10px 0 rgba(0, 0, 0, 1);
border-radius:10px;
opacity:0;
}
JavaScript:
var div = document.getElementById('wrapper');
var a = document.getElementById("a");
var fadeSpeed = 25; // a value between 1 and 1000 where 1000 will take 10
// seconds to fade in and out and 1 will take 0.01 sec.
var tipMessage = "The content of the tooltip...";
var showTip = function(){
var tip = document.createElement("span");
tip.className = "tooltip";
tip.id = "tip";
tip.innerHTML = tipMessage;
div.appendChild(tip);
tip.style.opacity="0"; // to start with...
var intId = setInterval(function(){
newOpacity = parseFloat(tip.style.opacity)+0.1;
tip.style.opacity = newOpacity.toString();
if(tip.style.opacity == "1"){
clearInterval(intId);
}
}, fadeSpeed);
};
var hideTip = function(){
var tip = document.getElementById("tip");
var intId = setInterval(function(){
newOpacity = parseFloat(tip.style.opacity)-0.1;
tip.style.opacity = newOpacity.toString();
if(tip.style.opacity == "0"){
clearInterval(intId);
tip.remove();
}
}, fadeSpeed);
tip.remove();
};
a.addEventListener("mouseover", showTip, false);
a.addEventListener("mouseout", hideTip, false);
You may be looking for the special HTML character,
.
You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt
label.
You can also do like the following: This will draw a 10x1 random matrix data on the plot for 50 cycles of the for loop.
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
for i in range(50):
y = np.random.random([10,1])
plt.plot(y)
plt.draw()
plt.pause(0.0001)
plt.clf()
For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
First, have to check
SELECT * FROM university
WHERE course_name LIKE '%&%'
Next, have to update
UPDATE university SET course_name = REPLACE(course_name, '&', '&') WHERE id = 1
Results: Engineering & Technology => Engineering & Technology
we can do that by doing a simple trick
a = 20;
b = 30;
a = a+b; // add both the number now a has value 50
b = a-b; // here we are extracting one number from the sum by sub
a = a-b; // the number so obtained in above help us to fetch the alternate number from sum
System.out.print("swapped numbers are a = "+ a+"b = "+ b);
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
dumps
takes an object and produces a string:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would take a file-like object, read the data from that object, and use that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
Note that dump
and load
convert between files and objects, while dumps
and loads
convert between strings and objects. You can think of the s
-less functions as wrappers around the s
functions:
def dump(obj, fh):
fh.write(dumps(obj))
def load(fh):
return loads(fh.read())
Simple use text = text + string2
Pre-increment ++i increments the value of i and evaluates to the new incremented value.
int i = 3;
int preIncrementResult = ++i;
Assert( preIncrementResult == 4 );
Assert( i == 4 );
Post-increment i++ increments the value of i and evaluates to the original non-incremented value.
int i = 3;
int postIncrementResult = i++;
Assert( postIncrementtResult == 3 );
Assert( i == 4 );
In C++, the pre-increment is usually preferred where you can use either.
This is because if you use post-increment, it can require the compiler to have to generate code that creates an extra temporary variable. This is because both the previous and new values of the variable being incremented need to be held somewhere because they may be needed elsewhere in the expression being evaluated.
So, in C++ at least, there can be a performance difference which guides your choice of which to use.
This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.
There's some more discussion here.
In C++ if you're using STL, then you may be using for loops with iterators. These mainly have overridden ++ operators, so sticking to pre-increment is a good idea. Compilers get smarter all the time though, and newer ones may be able to perform optimizations that mean there's no performance difference - especially if the type being incremented is defined inline in header file (as STL implementations often are) so that the compiler can see how the method is implemented and can then know what optimizations are safe to perform. Even so, it's probably still worth sticking to pre-increment because loops get executed lots of times and this means a small performance penalty could soon get amplified.
In other languages such as C# where the ++ operator can't be overloaded there is no performance difference. Used in a loop to advance the loop variable, the pre and post increment operators are equivalent.
Correction: overloading ++ in C# is allowed. It seems though, that compared to C++, in C# you cannot overload the pre and post versions independently. So, I would assume that if the result of calling ++ in C# is not assigned to a variable or used as part of a complex expression, then the compiler would reduce the pre and post versions of ++ down to code that performs equivalently.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:
//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;
map.setCenter(new google.maps.LatLng(
((lat_max + lat_min) / 2.0),
((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
//bottom left
new google.maps.LatLng(lat_min, lng_min),
//top right
new google.maps.LatLng(lat_max, lng_max)
));
Deep compare using a template of (nested) properties to check
function objetcsDeepEqualByTemplate(objectA, objectB, comparisonTemplate) {
if (!objectA || !objectB) return false
let areDifferent = false
Object.keys(comparisonTemplate).some((key) => {
if (typeof comparisonTemplate[key] === 'object') {
areDifferent = !objetcsDeepEqualByTemplate(objectA[key], objectB[key], comparisonTemplate[key])
return areDifferent
} else if (comparisonTemplate[key] === true) {
areDifferent = objectA[key] !== objectB[key]
return areDifferent
} else {
return false
}
})
return !areDifferent
}
const objA = {
a: 1,
b: {
a: 21,
b: 22,
},
c: 3,
}
const objB = {
a: 1,
b: {
a: 21,
b: 25,
},
c: true,
}
// template tells which props to compare
const comparisonTemplateA = {
a: true,
b: {
a: true
}
}
objetcsDeepEqualByTemplate(objA, objB, comparisonTemplateA)
// returns true
const comparisonTemplateB = {
a: true,
c: true
}
// returns false
objetcsDeepEqualByTemplate(objA, objB, comparisonTemplateB)
This will work in the console. Array support could be added if needed
A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.
This happened when i downloaded fabric.io on Eclipse Mars but Restarting computer solved this problem for me.
here is a working version :
function countbackgrounds() {
var book = SpreadsheetApp.getActiveSpreadsheet();
var range_input = book.getRange("B3:B4");
var range_output = book.getRange("B6");
var cell_colors = range_input.getBackgroundColors();
var color = "#58FA58";
var count = 0;
for( var i in cell_colors ){
Logger.log(cell_colors[i][0])
if( cell_colors[i][0] == color ){ ++count }
}
range_output.setValue(count);
}
Yes, it is a non-type parameter. You can have several kinds of template parameters
What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:
Template type parameter:
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
Template integer parameter:
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
Template pointer parameter (passing a pointer to a function)
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
Template reference parameter (passing an integer)
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
Template template parameter.
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
Syntactically, template<>
is reserved to mark an explicit template specialization, instead of a template without parameters:
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};
return array as string
>>> list(str(12345))
['1', '2', '3', '4', '5']
return array as integer
>>> map(int,str(12345))
[1, 2, 3, 4, 5]
For a very specific reason Type Nullable<int>
put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):
public struct Nullable<T> where T : struct
{
...
}
This is how I have achieved it using purely CSS and HTML (no JavaScript/images etc.).
It gracefully degrades in most browsers (I do need to add in a fix for lack of last-of-type in < IE9).
for i in range(a.count(' ')):
a.remove(' ')
Much simpler I believe.
While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length
property:
class slist(list):
@property
def length(self):
return len(self)
You can use it like so:
>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length
property.
As always, your mileage may vary.
Here's something that will print any sort of nested dictionary, while keeping track of the "parent" dictionaries along the way.
dicList = list()
def prettierPrint(dic, dicList):
count = 0
for key, value in dic.iteritems():
count+=1
if str(value) == 'OrderedDict()':
value = None
if not isinstance(value, dict):
print str(key) + ": " + str(value)
print str(key) + ' was found in the following path:',
print dicList
print '\n'
elif isinstance(value, dict):
dicList.append(key)
prettierPrint(value, dicList)
if dicList:
if count == len(dic):
dicList.pop()
count = 0
prettierPrint(dicExample, dicList)
This is a good starting point for printing according to different formats, like the one specified in OP. All you really need to do is operations around the Print blocks. Note that it looks to see if the value is 'OrderedDict()'. Depending on whether you're using something from Container datatypes Collections, you should make these sort of fail-safes so the elif block doesn't see it as an additional dictionary due to its name. As of now, an example dictionary like
example_dict = {'key1': 'value1',
'key2': 'value2',
'key3': {'key3a': 'value3a'},
'key4': {'key4a': {'key4aa': 'value4aa',
'key4ab': 'value4ab',
'key4ac': 'value4ac'},
'key4b': 'value4b'}
will print
key3a: value3a
key3a was found in the following path: ['key3']
key2: value2
key2 was found in the following path: []
key1: value1
key1 was found in the following path: []
key4ab: value4ab
key4ab was found in the following path: ['key4', 'key4a']
key4ac: value4ac
key4ac was found in the following path: ['key4', 'key4a']
key4aa: value4aa
key4aa was found in the following path: ['key4', 'key4a']
key4b: value4b
key4b was found in the following path: ['key4']
lastDict = list()
dicList = list()
def prettierPrint(dic, dicList):
global lastDict
count = 0
for key, value in dic.iteritems():
count+=1
if str(value) == 'OrderedDict()':
value = None
if not isinstance(value, dict):
if lastDict == dicList:
sameParents = True
else:
sameParents = False
if dicList and sameParents is not True:
spacing = ' ' * len(str(dicList))
print dicList
print spacing,
print str(value)
if dicList and sameParents is True:
print spacing,
print str(value)
lastDict = list(dicList)
elif isinstance(value, dict):
dicList.append(key)
prettierPrint(value, dicList)
if dicList:
if count == len(dic):
dicList.pop()
count = 0
Using the same example code, it will print the following:
['key3']
value3a
['key4', 'key4a']
value4ab
value4ac
value4aa
['key4']
value4b
This isn't exactly what is requested in OP. The difference is that a parent^n is still printed, instead of being absent and replaced with white-space. To get to OP's format, you'll need to do something like the following: iteratively compare dicList with the lastDict. You can do this by making a new dictionary and copying dicList's content to it, checking if i in the copied dictionary is the same as i in lastDict, and -- if it is -- writing whitespace to that i position using the string multiplier function.
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
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++;
}
}
Here's yet another alternative:
template<typename T>
void Remove( std::basic_string<T> & Str, const T * CharsToRemove )
{
std::basic_string<T>::size_type pos = 0;
while (( pos = Str.find_first_of( CharsToRemove, pos )) != std::basic_string<T>::npos )
{
Str.erase( pos, 1 );
}
}
std::string a ("(555) 555-5555");
Remove( a, "()-");
Works with std::string and std::wstring
In:
for i in range(c/10):
You're creating a float as a result - to fix this use the int division operator:
for i in range(c // 10):
every objects in Objective C conform to NSObject protocol, which holds onto the performSelector: method. I was also previously looking for a way to create some "helper or private" methods that I did not need exposed on a public level. If you want to create a private method with no overhead and not having to define it in your header file then give this a shot...
define the your method with a similar signature as the code below...
-(void)myHelperMethod: (id) sender{
// code here...
}
then when you need to reference the method simply call it as a selector...
[self performSelector:@selector(myHelperMethod:)];
this line of code will invoke the method you created and not have an annoying warning about not having it defined in the header file.
The only reason I can think of for using a numerical index in a set would be for iteration. For that, use
for(A a : set) {
visit(a);
}
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
In my case, I copied my class from somewhere else and didn't notice right away that it was an abstract
class. You can't inflate abstract classes.
You need to change:
{% endblock content %}
to
{% endblock %}
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
It is an issue with bad sql execution which does not allow other queries to execute until the previous one gets suspended/rollback.
In PgAdmin4-4.24 there is an option of rollback, one can try this.
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
this works for me (the width is forced by javascript and FB plugin loaded via javascript)
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId=443271375714375";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
jQuery(document).ready(function($) {
$(window).bind("load resize", function(){
setTimeout(function() {
var container_width = $('#container').width();
$('#container').html('<div class="fb-page" ' +
'data-href="http://www.facebook.com/IniciativaAutoMat"' +
' data-width="' + container_width + '" data-tabs="timeline" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="http://www.facebook.com/IniciativaAutoMat"><a href="http://www.facebook.com/IniciativaAutoMat">Auto*Mat</a></blockquote></div></div>');
FB.XFBML.parse( );
}, 100);
});
});
</script>
<div id="container" style="width:100%;">
<div class="fb-page" data-href="http://www.facebook.com/IniciativaAutoMat" data-tabs="timeline" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="http://www.facebook.com/IniciativaAutoMat"><a href="http://www.facebook.com/IniciativaAutoMat">Auto*Mat</a></blockquote></div></div>
</div>
I also met this problem just now and solved it in this way. So I recorded it here, and I wish it be useful for others.
Scenario:
The error occurred.
Solution:
There's many forms of timeout, are you after the connection timeout, request timeout or time to live (time before TCP connection stops).
The default TimeToLive on Firefox is 115s (network.http.keep-alive.timeout)
The default connection timeout on Firefox is 250s (network.http.connection-retry-timeout)
The default request timeout for Firefox is 30s (network.http.pipelining.read-timeout).
The time it takes to do an HttpRequest depends on if a connection has been made this has to be within 250s which I'm guessing you're not after. You're probably after the request timeout which I think is 30,000ms (30s) so to conclude I'd say it's timing out with a connection time out that's why you got a response back after ~150s though I haven't really tested this.
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
You need to have the database running before you create the users. For this you need multiple processes. You can either start postgres in a subshell (&) in the shell script, or use a tool like supervisord to run postgres and then run any initialization scripts.
A guide to supervisord and docker https://docs.docker.com/articles/using_supervisord/
There is no boot.ini on a machine with just Vista installed.
How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).
For the simple case check out GetSystemDirectory
I used this code, it is working fine
var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML)//run script inside div
Hi all Please try this property
$( "p span" ).last().addClass( "highlight" );
Thanks
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']
) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
Watch that your file name doesn't have :
in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt
and then scp no-colons.txt server:
then don't forget to mv
back on the server. Just in case this was an issue.
Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
This is what I usually do to "vertical align" text inside labels:
label {
display: block;
float: left;
padding-top: 2px; /*This needs to be modified to fit */
}
It won't scale very nicely, but it works.
For all who are interested in a swift extension, this is what I'm using now:
extension UINavigationController {
var rootViewController : UIViewController? {
return self.viewControllers.first
}
}
just to make the Answer 2 much easier, you can also define the folder where you can put your saved file
spool /home/admin/myoutputfile.txt
select * from table_name;
spool off;
after that only with nano or vi myoutputfile.txt, you will see all the sql track.
hope is that help :)
Just another option, which I wrote:
It's overkill if this is all the date processing that you need, but it will do what you want.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
It's better and safer to add to your LoginController.php the following code, that runs only after the standard logout:
use AuthenticatesUsers;
protected function loggedOut(Request $request)
{
return redirect('/new/redirect/you/want');
}
Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/
i notice they also user their own library in their website, so you can have a try using the browser console before installing it
moment().tz(String);
The moment#tz mutator will change the time zone and update the offset.
moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z'); // +01:00
This information is used consistently in other operations, like calculating the start of the day.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format(); // 2013-11-18T11:55:00-05:00
m.startOf("day").format(); // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format(); // 2013-11-18T00:00:00+01:00
Without an argument, moment#tz returns:
the time zone name assigned to the moment instance or
undefined if a time zone has not been set.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz(); // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined; // true
You could use setInterval
for this.
<script type="text/javascript">
function myFunction () {
console.log('Executed!');
}
var interval = setInterval(function () { myFunction(); }, 60000);
</script>
Disable the timer by setting clearInterval(interval)
.
See this Fiddle: http://jsfiddle.net/p6NJt/2/
If you want to just compare dates,
yourdatetime.date() < datetime.today().date()
Or, obviously,
yourdatetime.date() == datetime.today().date()
If you want to check that they're the same date.
The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about
. Unless your question is about a function/module named "snake".
Basically, the datetime
module has three types for storing a point in time:
date
for year, month, day of monthtime
for hours, minutes, seconds, microseconds, time zone infodatetime
combines date and time. It has the methods date()
and time()
to get the corresponding date
and time
objects, and there's a handy combine
function to combine date
and time
into a datetime
.Had this issue. My main app and extension belonged to the same app group id correctly, but there was also one more app ID not in my project that shared said app group id. I had to remove this last app ID's association with the app group.
I like this light weight http request client called `unirest'
gem install unirest
usage:
response = Unirest.post "http://httpbin.org/post",
headers:{ "Accept" => "application/json" },
parameters:{ :age => 23, :foo => "bar" }
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
To use Apache HTTP for SDK Level 23:
Top level build.gradle - /build.gradle
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// Lowest version for useLibrary is 1.3.0
// Android Studio will notify you about the latest stable version
// See all versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
}
...
}
Notification from Android studio about gradle update:
Module specific build.gradle - /app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
...
useLibrary 'org.apache.http.legacy'
...
}
The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.
But I came across a different scenario, which also covers the question asked.
What if you have to use an existing object list, like ViewData["htmlAttributes"]
in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... }
)?
For this slightly different scenario I want to share with you what I found out.
In the solutions below, I am assuming the following declaration for nodes
:
List<object> nodes = new List<object>();
nodes.Add(
new
{
Checked = false,
depth = 1,
id = "div_1"
});
In C# 4.0 and higher versions, you can simply cast to dynamic and write:
if (nodes.Any(n => ((dynamic)n).Checked == false))
Console.WriteLine("found a not checked element!");
Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked
property and throws a RuntimeBinderException
in this case - so if you try to use a non-existing Checked2
property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'"
.
The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.
Background
As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]
).
Inspired by the code in the link above, I created an extension class providing GetProp
, UnanonymizeProperties
and UnanonymizeListItems
as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:
if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
Console.WriteLine("found a not checked element!");
}
or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any()
as if
condition, which filters implicitly and then checks if there are any elements returned.
To get the first object containing "Checked" property and return its property "depth", you can use:
var depth = nodes.UnanonymizeListItems()
?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");
or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];
Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:
if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true));
return y.HasValue && y.Value == false;}).Any())
{
Console.WriteLine("found a not checked element!");
}
This prevents, that a KeyNotFoundException
occurs if the "Checked" property does not exist.
The class below contains the following extension methods:
UnanonymizeProperties
: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.UnanonymizeListItems
: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.GetProp
: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)For the examples above, all that is required is that you add the extension class below:
public static class AnonymousTypeExtensions
{
// makes properties of object accessible
public static IDictionary UnanonymizeProperties(this object obj)
{
Type type = obj?.GetType();
var properties = type?.GetProperties()
?.Select(n => n.Name)
?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
return properties;
}
// converts object list into list of properties that meet the filterCriteria
public static List<IDictionary> UnanonymizeListItems(this List<object> objectList,
Func<IDictionary<string, object>, bool> filterCriteria=default)
{
var accessibleList = new List<IDictionary>();
foreach (object obj in objectList)
{
var props = obj.UnanonymizeProperties();
if (filterCriteria == default
|| filterCriteria((IDictionary<string, object>)props) == true)
{ accessibleList.Add(props); }
}
return accessibleList;
}
// returns specific property, i.e. obj.GetProp(propertyName)
// requires prior usage of AccessListItems and selection of one element, because
// object needs to be a IDictionary<string, object>
public static object GetProp(this object obj, string propertyName,
bool treatNotFoundAsNull = false)
{
try
{
return ((System.Collections.Generic.IDictionary<string, object>)obj)
?[propertyName];
}
catch (KeyNotFoundException)
{
if (treatNotFoundAsNull) return default(object); else throw;
}
}
}
Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?.
by .
and ?[
by [
everywhere (and do the null-handling traditionally by using if
statements or catch NullReferenceExceptions), e.g.
var depth = nodes.UnanonymizeListItems()
.FirstOrDefault(n => n.Contains("Checked"))["depth"];
As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.
If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.
Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.
What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.
find . -type f |
sed -n "s/\(.*\)factory\.py$/& \1service\.py/p" |
xargs -p -n 2 mv
eg will rename all files in the cwd with names ending in "factory.py" to be replaced with names ending in "service.py"
explanation:
1) in the sed cmd, the -n flag will suppress normal behavior of echoing input to output after the s/// command is applied, and the p option on s/// will force writing to output if a substitution is made. since a sub will only be made on match, sed will only have output for files ending in "factory.py"
2) in the s/// replacement string, we use "& " to interpolate the entire matching string, followed by a space character, into the replacement. because of this, it's vital that our RE matches the entire filename. after the space char, we use "\1service.py" to interpolate the string we gulped before "factory.py", followed by "service.py", replacing it. So for more complex transformations youll have to change the args to s/// (with an re still matching the entire filename)
example output:
foo_factory.py foo_service.py
bar_factory.py bar_service.py
3) we use xargs with -n 2 to consume the output of sed 2 delimited strings at a time, passing these to mv (i also put the -p option in there so you can feel safe when running this). voila.
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
Source article: Passing a list as an argument to a vararg method
Use the toArray(T[] arr)
method.
.getMap(locations.toArray(new WorldLocation[locations.size()]))
(toArray(new WorldLocation[0])
also works, but you would allocate a zero-length array for no reason.)
Here's a complete example:
public static void method(String... strs) {
for (String s : strs)
System.out.println(s);
}
...
List<String> strs = new ArrayList<String>();
strs.add("hello");
strs.add("world");
method(strs.toArray(new String[strs.size()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
Since fields
or fns
are cell arrays, you have to index with curly brackets {}
in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields
directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end