This should fix the error
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
</plugin>
If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER
This is my project error when I try to vilidated.
Finally follow this ANSWER, error solved.
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
In Python 3.x
, simply use get(attr_name)
on your tag object that you get using find_all
:
xmlData = None
with open('conf//test1.xml', 'r') as xmlFile:
xmlData = xmlFile.read()
xmlDecoded = xmlData
xmlSoup = BeautifulSoup(xmlData, 'html.parser')
repElemList = xmlSoup.find_all('repeatingelement')
for repElem in repElemList:
print("Processing repElem...")
repElemID = repElem.get('id')
repElemName = repElem.get('name')
print("Attribute id = %s" % repElemID)
print("Attribute name = %s" % repElemName)
against XML file conf//test1.xml
that looks like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<singleElement>
<subElementX>XYZ</subElementX>
</singleElement>
<repeatingElement id="11" name="Joe"/>
<repeatingElement id="12" name="Mary"/>
</root>
prints:
Processing repElem...
Attribute id = 11
Attribute name = Joe
Processing repElem...
Attribute id = 12
Attribute name = Mary
For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState
here's my solution:
const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);
const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
setAnchorElement(event.currentTarget);
};
From w3schools.com: Made compatible with Firefox Sept, 2016
<input type="text" onfocusout="myFunction()">
I'm using:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", DEFAULT_NAMESPACE);
using (var stream = new MemoryStream())
{
var someone = new Person
{
FirstName = "Donald",
LastName = "Duck"
};
serializer.Serialize(stream, someone, namespaces);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
To get the following XML:
<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
<FirstName>Donald</FirstName>
<LastName>Duck</LastName>
</Person>
If you don't want the namespace, just set DEFAULT_NAMESPACE to "".
For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.
The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)
Using this regex:
^(?!.*function).*(\&\$)
it is possible to search project-wide for the occurrence of &$
only in lines that are not a function definition.
This still turns up a lot of false positives, but it does make the job easier.
VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.
Nested JSON
object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type
and data.view.note
JSON
Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type
and data.view[0].note
"Unlink" essentially means "delete file" in this case.
This error is not caused by git itself. You should have similar errors deleting those files manually, in a command line or file explorer.
Here are the commands I use to get the contents of the queue:
RabbitMQ version 3.1.5 on Fedora linux using https://www.rabbitmq.com/management-cli.html
Here are my exchanges:
eric@dev ~ $ sudo python rabbitmqadmin list exchanges
+-------+--------------------+---------+-------------+---------+----------+
| vhost | name | type | auto_delete | durable | internal |
+-------+--------------------+---------+-------------+---------+----------+
| / | | direct | False | True | False |
| / | kowalski | topic | False | True | False |
+-------+--------------------+---------+-------------+---------+----------+
Here is my queue:
eric@dev ~ $ sudo python rabbitmqadmin list queues
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
| vhost | name | auto_delete | consumers | durable | exclusive_consumer_tag | idle_since | memory | messages | messages_ready | messages_unacknowledged | node | policy | status |
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
| / | myqueue | False | 0 | True | | 2014-09-10 13:32:18 | 13760 | 0 | 0 | 0 |rabbit@ip-11-1-52-125| | running |
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
Cram some items into myqueue:
curl -i -u guest:guest http://localhost:15672/api/exchanges/%2f/kowalski/publish -d '{"properties":{},"routing_key":"abcxyz","payload":"foobar","payload_encoding":"string"}'
HTTP/1.1 200 OK
Server: MochiWeb/1.1 WebMachine/1.10.0 (never breaks eye contact)
Date: Wed, 10 Sep 2014 17:46:59 GMT
content-type: application/json
Content-Length: 15
Cache-Control: no-cache
{"routed":true}
RabbitMQ see messages in queue:
eric@dev ~ $ sudo python rabbitmqadmin get queue=myqueue requeue=true count=10
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
| routing_key | exchange | message_count | payload | payload_bytes | payload_encoding | properties | redelivered |
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
| abcxyz | kowalski | 10 | foobar | 6 | string | | True |
| abcxyz | kowalski | 9 | {'testdata':'test'} | 19 | string | | True |
| abcxyz | kowalski | 8 | {'mykey':'myvalue'} | 19 | string | | True |
| abcxyz | kowalski | 7 | {'mykey':'myvalue'} | 19 | string | | True |
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
First type
nvidia-smi
then select the PID that you want to kill
sudo kill -9 PID
First of all: Yes you can mix jQuery with common JS :)
Best way to build up an intervall call of a function is to use setTimeout methode:
For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:
function test(){
console.log('test called');
setTimeout(test, 5000);
}
Finally you have to trigger the function once:
$(document).ready(function(){
test();
});
This document ready function is called automatically, after all html is loaded.
It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.
How to Authenticate Git using Access Tokens
Wow, it works!
You don't quite have SQL Server's proprietary UPDATE FROM
syntax down. Also not sure why you needed to join on the CommonField
and also filter on it afterward. Try this:
UPDATE t1
SET t1.CalculatedColumn = t2.[Calculated Column]
FROM dbo.Table1 AS t1
INNER JOIN dbo.Table2 AS t2
ON t1.CommonField = t2.[Common Field]
WHERE t1.BatchNo = '110';
If you're doing something really silly - like constantly trying to set the value of one column to the aggregate of another column (which violates the principle of avoiding storing redundant data), you can use a CTE (common table expression) - see here and here for more details:
;WITH t2 AS
(
SELECT [key], CalculatedColumn = SUM(some_column)
FROM dbo.table2
GROUP BY [key]
)
UPDATE t1
SET t1.CalculatedColumn = t2.CalculatedColumn
FROM dbo.table1 AS t1
INNER JOIN t2
ON t1.[key] = t2.[key];
The reason this is really silly, is that you're going to have to re-run this entire update every single time any row in table2
changes. A SUM
is something you can always calculate at runtime and, in doing so, never have to worry that the result is stale.
jQuery dialog has an isOpen
property that can be used to check if a jQuery dialog is open or not.
You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html
Disabling the Program Compatibility Assistant is not the right way.
A solution that works on Windows 10 is:
Properties
and navigate to the Details
tab. Original filename
. Simply rename the file accordingly and it should run.man printf.1
has a note at the bottom: "...your shell may have its own version of printf
...". This question is tagged for bash
, but if at all possible, I try to write scripts portable to any shell. dash
is usually a good minimum baseline for portability - so the answer here works in bash
, dash
, & zsh
. If a script works in those 3, it's most likely portable to just about anywhere.
The latest implementation of printf
in dash
[1] doesn't colorize output given a %s
format specifier with an ANSI escape character \e
-- but, a format specifier %b
combined with octal \033
(equivalent to an ASCII ESC
) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf
to use the ASCII octal subset at a bare minimum.
To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b
format specifier for printf
(as referenced in an earlier answer from @Vlad) with an octal escape \033
.
portable-color.sh
#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"
Outputs:
$ ./portable-color.sh
-> This is \033[1;34m blue \033[0m text
-> This is blue text
...and 'blue' is blue in the second line.
The %-6s
format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.
[1] Ref: man dash
Section "Builtins" :: "printf" :: "Format"
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
I prefer skipping it, I read somewhere that interfaces are by default, public
and abstract
.
To my surprise the book - Head First Design Patterns, is using public
with interface declaration and interface methods... that made me rethink once again and I landed up on this post.
Anyways, I think redundant information should be ignored.
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
This is the correct and easiest way to accomplish this for 95% of use cases:
>>> df = pd.DataFrame(zip(*[range(10)]), columns=['num'])
>>> df
num
0 0
1 1
2 2
3 3
4 4
5 5
>>> def example(x):
... x['p1'] = x['num']**2
... x['p2'] = x['num']**3
... x['p3'] = x['num']**4
... return x
>>> df = df.apply(example, axis=1)
>>> df
num p1 p2 p3
0 0 0 0 0
1 1 1 1 1
2 2 4 8 16
3 3 9 27 81
4 4 16 64 256
I'd consider also Apache Thrift http://thrift.apache.org/
It can bridge between several programming languages, is highly efficient and has support for async or sync calls. See full features here http://thrift.apache.org/docs/features/
The multi language can be useful for future plans, for example if you later want to do part of the computational task in C++ it's very easy to do add it to the mix using Thrift.
Let's assume you have install
target, which is a very common in makefiles. If you do not use .PHONY
, and a file named install
exists in the same directory as the Makefile, then make install
will do nothing. This is because Make interprets the rule to mean "execute such-and-such recipe to create the file named install
". Since the file is already there, and its dependencies didn't change, nothing will be done.
However if you make the install
target PHONY, it will tell the make tool that the target is fictional, and that make should not expect it to create the actual file. Hence it will not check whether the install
file exists, meaning: a) its behavior will not be altered if the file does exist and b) extra stat()
will not be called.
Generally all targets in your Makefile which do not produce an output file with the same name as the target name should be PHONY. This typically includes all
, install
, clean
, distclean
, and so on.
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.
If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:
public string CreateFile(string id, string name, string description,
/* --> */ SupportedPermissions supportedPermissions)
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = supportedPermissions // <---
};
return file.Id;
}
If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:
public string CreateFile(string id, string name, string description) // <---
{
file = new File
{
Name = name,
Id = id,
Description = description,
SupportedPermissions = SupportedPermissions.basic // <---
};
return file.Id;
}
for simple comments:
set serveroutput on format wrapped;
begin
DBMS_OUTPUT.put_line('simple comment');
end;
/
-- do something
begin
DBMS_OUTPUT.put_line('second simple comment');
end;
/
you should get:
anonymous block completed
simple comment
anonymous block completed
second simple comment
if you want to print out the results of variables, here's another example:
set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
DBMS_OUTPUT.put_line(a_comment);
end;
/
-- do something
declare
a_comment VARCHAR2(200) :='comment';
begin
DBMS_OUTPUT.put_line(a_comment || 2);
end;
your output should be:
anonymous block completed
first comment
anonymous block completed
comment2
If for a some reason can't use rsyslog, this will do:
ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"
You could set up the following alias in your bash profile:
alias s='it=$($(history | tail -2 | head -1 | cut -d" " -f4-))'
Then, by typing 's' after an arbitrary command you can save the result to a shell variable 'it'.
So example usage would be:
$ which python
/usr/bin/python
$ s
$ file $it
/usr/bin/python: symbolic link to `python2.6'
If you use python 3
python3 -m pip install pylint-django
If python < 3
python -m pip install pylint-django==0.11.1
NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)
Use a vertical bar (|
) for "or".
case "$C" in
"1")
do_this()
;;
"2" | "3")
do_what_you_are_supposed_to_do()
;;
*)
do_nothing()
;;
esac
DECLARE
a VARCHAR2(30);
b VARCHAR2(30);
c VARCHAR2(30);
BEGIN
a := ' Abc ';
b := ' def ';
c := a || b;
DBMS_OUTPUT.PUT_LINE(c);
END;
output:: Abc def
I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:
https://github.com/cxong/tinydir
tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");
while (dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
printf("%s", file.name);
if (file.is_dir)
{
printf("/");
}
printf("\n");
tinydir_next(&dir);
}
tinydir_close(&dir);
You can create a custom control that inherits from the Button class. This code will be more reusable, please look at the following blog post for more details: WPF - create custom button with image (ImageButton)
Using this control:
<local:ImageButton Width="200" Height="50" Content="Click Me!"
ImageSource="ok.png" ImageLocation="Left" ImageWidth="20" ImageHeight="25" />
ImageButton.cs file:
public class ImageButton : Button
{
static ImageButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));
}
public ImageButton()
{
this.SetCurrentValue(ImageButton.ImageLocationProperty, WpfImageButton.ImageLocation.Left);
}
public int ImageWidth
{
get { return (int)GetValue(ImageWidthProperty); }
set { SetValue(ImageWidthProperty, value); }
}
public static readonly DependencyProperty ImageWidthProperty =
DependencyProperty.Register("ImageWidth", typeof(int), typeof(ImageButton), new PropertyMetadata(30));
public int ImageHeight
{
get { return (int)GetValue(ImageHeightProperty); }
set { SetValue(ImageHeightProperty, value); }
}
public static readonly DependencyProperty ImageHeightProperty =
DependencyProperty.Register("ImageHeight", typeof(int), typeof(ImageButton), new PropertyMetadata(30));
public ImageLocation? ImageLocation
{
get { return (ImageLocation)GetValue(ImageLocationProperty); }
set { SetValue(ImageLocationProperty, value); }
}
public static readonly DependencyProperty ImageLocationProperty =
DependencyProperty.Register("ImageLocation", typeof(ImageLocation?), typeof(ImageButton), new PropertyMetadata(null, PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var imageButton = (ImageButton)d;
var newLocation = (ImageLocation?) e.NewValue ?? WpfImageButton.ImageLocation.Left;
switch (newLocation)
{
case WpfImageButton.ImageLocation.Left:
imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 0);
break;
case WpfImageButton.ImageLocation.Top:
imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 0);
imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
break;
case WpfImageButton.ImageLocation.Right:
imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 2);
break;
case WpfImageButton.ImageLocation.Bottom:
imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 2);
imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
break;
case WpfImageButton.ImageLocation.Center:
imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null));
public int RowIndex
{
get { return (int)GetValue(RowIndexProperty); }
set { SetValue(RowIndexProperty, value); }
}
public static readonly DependencyProperty RowIndexProperty =
DependencyProperty.Register("RowIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));
public int ColumnIndex
{
get { return (int)GetValue(ColumnIndexProperty); }
set { SetValue(ColumnIndexProperty, value); }
}
public static readonly DependencyProperty ColumnIndexProperty =
DependencyProperty.Register("ColumnIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));
}
public enum ImageLocation
{
Left,
Top,
Right,
Bottom,
Center
}
Generic.xaml file:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfImageButton">
<Style TargetType="{x:Type local:ImageButton}" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding ImageSource, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
Width="{Binding ImageWidth, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
Height="{Binding ImageHeight, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
Grid.Row="{Binding RowIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
Grid.Column="{Binding ColumnIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
VerticalAlignment="Center" HorizontalAlignment="Center"></Image>
<ContentPresenter Grid.Row="1" Grid.Column="1" Content="{TemplateBinding Content}"
VerticalAlignment="Center" HorizontalAlignment="Center"></ContentPresenter>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Try:
select distinct T1.id
from TABLE1 T1
where not exists (select distinct T2.id
from TABLE2 T2
where T2.id = T1.id)
With sql oracle 11g+
No matter how many times you call the operation, the result will be the same.
check that "filename.exe" is not running, I guess you are using Microsoft Windows, in that case you can use either Task Manager or Process Explorer : http://technet.microsoft.com/en-us/sysinternals/bb896653 to kill "filename.exe" before trying to generate it.
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
You can try this...
<div class="image">
<img src="" alt="" />
<h2>Text you want to display over the image</h2>
</div>
CSS
.image {
position: relative;
width: 100%; /* for IE 6 */
}
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
You may need user name and password:
mysqlcheck -A --auto-repair -uroot -p
You will be prompted for password.
mysqlcheck -A --auto-repair -uroot -p{{password here}}
If you want to put in cron, BUT your password will be visible in plain text!
I used the answer from Jonathan to google inserting images into LaTeX and if you would like to insert an image named image1.jpg and have it centered, your code might look like this in Rmarkdown
\begin{center}
\includegraphics{image1}
\end{center}
Keep in mind that LaTex is not asking for the file exention (.jpg). This question helped me get my answer. Thanks.
PHP's DateTime
object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
$date = new DateTime($date,new DateTimeZone($timezone));
$date->setTimezone( new DateTimeZone($timezone_to) );
return $date->format($format);
}
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
In SQL Server 2012 you can do this :
Declare @Count1 int ;
Select @Count1 = Count(*)
FROM [Log] AS L
SELECT
*
FROM [Log] AS L
ORDER BY L.id
OFFSET @Count - 5 ROWS
FETCH NEXT 5 ROWS ONLY;
I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img
files all the time.
Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount
"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...
So, how to get the file from the inside of userdata.img?"
To load .img
files you have to select loop and load the .img
Select loop
Next you select mount Select mount
Furius ISO mount handles all the other options loading the .img
file to your /home/dir.
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
You can Use ngValue
. ngValue
passes sting and object both.
Pass as Object:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj.value">
{{obj.value}}
</option>
</select>
Pass as String:
<select (change)="onItemChange($event.value)">
<option *ngFor="#obj of arr" [ngValue]="obj">
{{obj.value}}
</option>
</select>
To get parent window handles.
String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
String currentHandle ="";
Set<String> win = ts.getDriver().getWindowHandles();
Iterator<String> it = win.iterator();
if(win.size() > 1){
while(it.hasNext()){
String handle = it.next();
if (!handle.equalsIgnoreCase(parentHandle)){
ts.getDriver().switchTo().window(handle);
currentHandle = handle;
}
}
}
else{
System.out.println("Unable to switch");
}
return currentHandle;
}
Use it to achieve what you want. Then decide which properties you want to return.
yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER
documentation:
Caution must be exercised when specifying an unencrypted password with this command. The password will be transmitted to the server in cleartext, and it might also be logged in the client's command history or the server log. psql contains a command \password that can be used to change a role's password without exposing the cleartext password.
Note: ALTER USER
is an alias for ALTER ROLE
If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:
struct bitfield{
unsigned int bit : 1
}
struct bitfield *bitstream;
then later on load it like this (replacing char with int or whatever data you are loading):
long int i;
int j, k;
unsigned char c, d;
bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
c=charstream[i];
for(j=0; j < sizeof(char)*8; j++){
d=c;
d=d>>(sizeof(char)*8-j-1);
d=d<<(sizeof(char)*8-1);
k=d;
if(k==0){
bitstream[sizeof(char)*8*i + j].bit=0;
}else{
bitstream[sizeof(char)*8*i + j].bit=1;
}
}
}
Then access elements:
bitstream[bitpointer].bit=...
or
...=bitstream[bitpointer].bit
All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.
IIRC, something like:
set tabstop=2 shiftwidth=2 expandtab
should do the trick. If you already have tabs, then follow it up with a nice global RE to replace them with double spaces.
If you already have tabs you want to replace,
:retab
The accepted answer seems not work for me. My solution:
import time
utc_0 = int(time.mktime(datetime(1970, 01, 01).timetuple()))
def datetime2ts(dt):
"""Converts a datetime object to UTC timestamp"""
return int(time.mktime(dt.utctimetuple())) - utc_0
Bravo JSP Editor (Can't comment on how good it is, i haven't tried it) http://marketplace.eclipse.org/content/bravo-jsp-editor
This is what I ended up using a variation of, which checks for IE8 and below:
if (preg_match('/MSIE\s(?P<v>\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B) && $B['v'] <= 8) {
// Browsers IE 8 and below
} else {
// All other browsers
}
I use this simple method:
public Dictionary<string, string> objToDict(XYZ.ObjectCollection objs) {
var dict = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> each in objs){
dict.Add(each.Key, each.Value);
}
return dict;
}
Not sure if JSF provides a built-in functionality, but you could use java.sql.Date
's constructor to convert to a date object: http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html#Date(long)
Then you should be able to use higher level features provided by Java SE, Java EE to display and format the extracted date. You could instantiate a java.util.Calendar
and explicitly set the time: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#setTime(java.util.Date)
EDIT: The JSF components should not take care of the conversion. Your data access layer (persistence layer) should take care of this. In other words, your JSF components should not handle the long
typed attributes but only a Date
or Calendar
typed attributes.
Try this:
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
function getPaging(str)
{
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
It looks like get-pip.py
has been updated to use the environment variables http_proxy
and https_proxy
.
Windows:
set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
python get-pip.py
Linux/OS X:
export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E python get-pip.py
However if this still doesn't work for you, you can always install pip through a proxy using setuptools' easy_install
by setting the same environment variables.
Windows:
set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
easy_install pip
Linux/OS X:
export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E easy_install pip
Then once it's installed, use:
pip install --proxy="user:password@server:port" packagename
From the pip man page:
--proxy
Have pip use a proxy server to access sites. This can be specified using "user:[email protected]:port" notation. If the password is left out, pip will ask for it.
Alright, this doesn't apply to the OP's exact situation, but for anyone like myself who comes here facing a similar issue, figure I should throw this out there-- maybe save a headache or two.
If you're using an non-standard "button" to ensure the submit
event isn't called:
<form>
<input type="hidden" name="hide" value="1">
<a href="#" onclick="submitWithChecked(this.form)">Hide Selected</a>
</form>
Then, when you try to access this.form
in the script, it's going to come up undefined. As I discovered, apparently anchor elements don't have same access to a parent form
element the way your standard form elements do.
In such cases, (again, assuming you are intentionally avoiding the submit
event for the time-being), you can use a button
with type="button"
<form>
<input type="hidden" name="hide" value="1">
<button type="button" onclick="submitWithChecked(this.form)">Hide Selected</a>
</form>
(Addendum 2020: All these years later, I think the more important lesson to take away from this is to check your input. If my function had bothered to check that the argument it received was actually a form element, the problem would have been much easier to catch.)
You can prefix the function declaration with extern “C” keyword, e.g.
extern “C” int Mycppfunction()
{
// Code goes here
return 0;
}
For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.
I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
Note only use this code if you are sure that removing the alpha would not affect anything.
You can use in this manner also
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
I have tried all above methods but none of them work for me.
Then I came up with my own solution.
First of all, you need a clean, up-to-date local repo. Delete all the fucking large files.
Now create a new folder OUTSIDE of your repo folder and use "Git create repository here" to make it a new Git repository, let's call it new_local_repo. This is it! All above methods said you have to clean the history..., well, I'm sick of that, let's create a new repo which has no history at all!
Copy the files from your old, fucked up local repo to the new, beautiful repo. Note that the green logo on the folder icon will disappear, this is promising because this is a new repo!
Commit to the local branch and then push to remote new branch. Let's call it new_remote_branch. If you don't know how to push from a new local repo, Google it.
Congrats! You have pushed your clean, up-to-date code to GitHub. If you don't need the remote master branch anymore, you can make your new_remote_branch as new master branch. If you don't know how to do it, Google it.
Last step, it's time to delete the fucked up old local repo. In the future you only use the new_local_repo.
SELECT group, date, checks
FROM table
WHERE checks > 0
GROUP BY group HAVING date = max(date)
should work.
This will not work correctly, e.g. abcÑxyz
will pass thru this as it has a,b,c... you need to work with Collate or check each byte.
No you can not but you may want to use input type number as a workaround. Look at the following example:
<input type="number" min="1900" max="2099" step="1" value="2016" />
From Google Code FAQ - Creating a Store Locator with PHP, MySQL & Google Maps:
Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance
FROM markers
HAVING distance < 25
ORDER BY distance
LIMIT 0 , 20;
After all the changes, when you push all these commands, you might have to use:
git push -f ...
And not only git push
.
A float has 23 bits of precision, and a double has 52.
Iterables.elementsEqual
is best choice:Iterables.elementsEqual
is enough to compare 2 List
s.
Iterables.elementsEqual
is used in more general scenarios, It accepts more general types: Iterable
. That is, you could even compare a List
with a Set
. (by iterate order, it is important)
Sure ArrayList
and LinkedList
define equals pretty good, you could call equals directly. While when you use a not well defined List, Iterables.elementsEqual
is the best choice. One thing should be noticed: Iterables.elementsEqual
does not accept null
To convert List to array: Iterables.toArray
is easer.
For unit test, I recommend add empty list to your test case.
I got same error after publish my project to my physical server. My web application works perfectly on my computer when I compile on VS2013
. When I checked connection string on sql server manager, everything works perfect on server too. I also checked firewall (I switched it off). But still didn't work. I remotely try to connect database by SQL Manager with exactly same user/pass and instance name etc with protocol pipe/tcp and I saw that everything working normally. But when I try to open website I'm getting this error. Is there anyone know 4th option for fix this problem?.
NOTE: My App: ASP.NET 4.5 (by VS2013)
, Server: Windows 2008 R2 64bit
, SQL: MS-SQL WEB 2012 SP1
Also other web applications works great at web browsers with their database on same server.
After one day suffering I found the solution of my issue:
First I checked all the logs and other details but i could find nothing. Suddenly I recognize that; when I try to use connection string which is connecting directly to published DB and run application on my computer by VS2013, I saw that it's connecting another database file. I checked local directories and I found it. ASP.NET Identity not using my connection string as I wrote in web.config file. And because of this VS2013 is creating or connecting a new database with the name "DefaultConnection.mdf" in App_Data folder. Then I found the solution, it was in IdentityModel.cs.
I changed code as this:
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//public ApplicationDbContext() : base("DefaultConnection") ---> this was original
public ApplicationDbContext() : base("<myConnectionStringNameInWebConfigFile>") //--> changed
{
}
}
So, after all, I re-builded and published my project and everything works fine now :)
If you have no concrete implementations of the class and the methods aren't static
whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.
I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected
and public
, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.
If you want to count the number of records in your table, simply run:
SELECT COUNT(*) FROM your_table;
Starting with parameter:
setup.exe /A
asks for saving included files (including MSI
).
This may depend on the software which created the setup.exe
.
if you have a checkbox and you would like to fetch it's value ie true / false in any java file--
Use--
Context mContext;
boolean checkFlag;
checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
Note: When you consider onclick="this.select()"
, At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters again but it will select all characters again. To fix this problem you should use onfocus
instead of onclick
.
Use -50%
instead of +50%
They will be aligned to left..
You can do it with 1 printf
:
System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/
This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.
Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).
(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
Here is the simple bug free solution (with source code), It is working for me.
Derive your ViewModel from INotifyPropertyChanged
Create a observable property CloseDialog in ViewModel
public void Execute()
{
// Do your task here
// if task successful, assign true to CloseDialog
CloseDialog = true;
}
private bool _closeDialog;
public bool CloseDialog
{
get { return _closeDialog; }
set { _closeDialog = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string property = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
Attach a Handler in View for this property change
_loginDialogViewModel = new LoginDialogViewModel();
loginPanel.DataContext = _loginDialogViewModel;
_loginDialogViewModel.PropertyChanged += OnPropertyChanged;
Now you are almost done. In the event handler make DialogResult = true
protected void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "CloseDialog")
{
DialogResult = true;
}
}
Template:
<input ng-click="check(profileForm.$valid)" name="submit"
id="submit" value="Save" class="submit" type="submit">
Controller:
$scope.check = function(value) {
if (value) {
updateMyProfile();
}
}
As my previous answer appeared not to be very popular, I will give this another go.
You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst()
.flatMap( Function.identity() );
This will fit all your requirements:
Optional<Result>
this::resolve
lazily as neededthis::resolve
will not be called after first non-empty resultOptional<Result>
The only modification compared to OP initial version was that I removed .map(Optional::get)
before call to .findFirst()
and added .flatMap(o -> o)
as the last call in the chain.
This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.
You can't really go any shorter than this in Java.
The alternative snippet of code using the more conventional for
loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:
this.resolve
, Optional.isPresent
Just to prove that my solution works as advertised, I wrote a small test program:
public class StackOverflow {
public static void main( String... args ) {
try {
final int integer = Stream.of( args )
.peek( s -> System.out.println( "Looking at " + s ) )
.map( StackOverflow::resolve )
.filter( Optional::isPresent )
.findFirst()
.flatMap( o -> o )
.orElseThrow( NoSuchElementException::new )
.intValue();
System.out.println( "First integer found is " + integer );
}
catch ( NoSuchElementException e ) {
System.out.println( "No integers provided!" );
}
}
private static Optional<Integer> resolve( String string ) {
try {
return Optional.of( Integer.valueOf( string ) );
}
catch ( NumberFormatException e )
{
System.out.println( '"' + string + '"' + " is not an integer");
return Optional.empty();
}
}
}
(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)
Executing this on a command line, I got the following results:
$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3
Do you want to disable error reporting, or just prevent the user from seeing it? It’s usually a good idea to log errors, even on a production site.
# in your PHP code:
ini_set('display_errors', '0'); # don't show any errors...
error_reporting(E_ALL | E_STRICT); # ...but do log them
They will be logged to your standard system log, or use the error_log
directive to specify exactly where you want errors to go.
Python isn't preprocessed. You can just create a file myconstants.py
:
MY_CONSTANT = 50
And importing them will just work:
import myconstants
print myconstants.MY_CONSTANT * 2
Don't skip John Papa's presentation from PDC Conference 2010. See it here.
Build-timeout Plugin can come handy for such cases. It will kill the job automatically if it takes too long.
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
From the grep(1)
man page:
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
object --> is Java class to convert it to XML
name --> is just name space like thing - for differentiate
public static String convertObjectToXML(Object object,String name) {
try {
StringWriter stringWriter = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qName = new QName(object.getClass().toString(), name);
Object root = new JAXBElement<Object>(qName,java.lang.Object.class, object);
jaxbMarshaller.marshal(root, stringWriter);
String result = stringWriter.toString();
System.out.println(result);
return result;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
Those are optional settings. Leave it set as Unknown and you should be good.
Edit: If "unknown" is no longer an option, try leaving everything in that section blank.
Be careful all of the other answers have some problem in IE.
Lets have this situation - button with prepended icon. All browsers handles this correctly, but IE takes the width of the element and scales the before content to fit it. JSFiddle
#mydiv1 { width: 200px; height: 30px; background: green; }
#mydiv1:before {
content: url("data:url or /standard/url.svg");
}
Solution is to set size to before element and leave it where it is:
#mydiv2 { width: 200px; height: 30px; background: green; }
#mydiv2:before {
content: url("data:url or /standard/url.svg");
display: inline-block;
width: 16px; //only one size is alright, IE scales uniformly to fit it
}
The background-image
+ background-size
solutions works as well, but is little unhandy, since you have to specify the same sizes twice.
The result in IE11:
Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.
ie:
IF(@Trans_type = 'subscr_signup')
set @tmpType = 'premium'
ELSE iF(@Trans_type = 'subscr_cancel')
set @tmpType = 'basic'
All solutions seems to be complicated. I'm looking for the simplest solution for this case and I just want to use constants. Constants are simple. Is there anything which speaks against the following solution?
app.const.ts
'use strict';
export const dist = '../path/to/dist/';
app.service.ts
import * as AppConst from '../app.const';
@Injectable()
export class AppService {
constructor (
) {
console.log('dist path', AppConst.dist );
}
}
With bash
a="The cat sat on the mat"
b=cat
strindex() {
x="${1%%$2*}"
[[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b" # prints 4
strindex "$a" foo # prints -1
Just wrap a
tag around all the HTML extract, for example
<a href="/categories/1">
<img alt="test1" class="img-responsive" src="/assets/photo.jpg" />
<div class="caption bg-orange">
<h2>
test1
</h2>
</div>
</a>
in my example my caption class has hover effects, that with pointer-events:none; you just will lose
wrapping the content will keep your hover effects and you can click in all the picture, div included, regards!
If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":
You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.
Use the following attribute:
cls.__bases__
From the docs:
The tuple of base classes of a class object.
Example:
>>> str.__bases__
(<type 'basestring'>,)
Another example:
>>> class A(object):
... pass
...
>>> class B(object):
... pass
...
>>> class C(A, B):
... pass
...
>>> C.__bases__
(<class '__main__.A'>, <class '__main__.B'>)
Two problems:
You write that you ran
git init
git commit -m "first commit"
and that, at that stage, you got
nothing added to commit but untracked files present (use "git add" to track).
Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):
Hey Git, you see that
README.md
file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...
For that you need to stage the files of interest, using
git add README.md
before running
git commit -m "some descriptive message"
You then ran
git remote add origin https://github.com/VijayNew/NewExample.git
After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get
Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with
git push -u origin master
The hacky, practical answer for people trying to evaluate which Heroku plan they need and can't wait for heroku's slow row counter to refresh:
Basically you want to run \dt
in psql
, copy the results to your favorite text editor (it will look like this:
public | auth_group | table | axrsosvelhutvw
public | auth_group_permissions | table | axrsosvelhutvw
public | auth_permission | table | axrsosvelhutvw
public | auth_user | table | axrsosvelhutvw
public | auth_user_groups | table | axrsosvelhutvw
public | auth_user_user_permissions | table | axrsosvelhutvw
public | background_task | table | axrsosvelhutvw
public | django_admin_log | table | axrsosvelhutvw
public | django_content_type | table | axrsosvelhutvw
public | django_migrations | table | axrsosvelhutvw
public | django_session | table | axrsosvelhutvw
public | exercises_assignment | table | axrsosvelhutvw
), then run a regex search and replace like this:
^[^|]*\|\s+([^|]*?)\s+\| table \|.*$
to:
select '\1', count(*) from \1 union/g
which will yield you something very similar to this:
select 'auth_group', count(*) from auth_group union
select 'auth_group_permissions', count(*) from auth_group_permissions union
select 'auth_permission', count(*) from auth_permission union
select 'auth_user', count(*) from auth_user union
select 'auth_user_groups', count(*) from auth_user_groups union
select 'auth_user_user_permissions', count(*) from auth_user_user_permissions union
select 'background_task', count(*) from background_task union
select 'django_admin_log', count(*) from django_admin_log union
select 'django_content_type', count(*) from django_content_type union
select 'django_migrations', count(*) from django_migrations union
select 'django_session', count(*) from django_session
;
(You'll need to remove the last union
and add the semicolon at the end manually)
Run it in psql
and you're done.
?column? | count
--------------------------------+-------
auth_group_permissions | 0
auth_user_user_permissions | 0
django_session | 1306
django_content_type | 17
auth_user_groups | 162
django_admin_log | 9106
django_migrations | 19
[..]
CREATE PROCEDURE [dbo].[Temp_Proc_Select_City]
@StateId INT
AS
BEGIN
SELECT * FROM tbl_City
WHERE
@StateID = CASE WHEN ISNULL(@StateId,0) = 0 THEN 0 ELSE StateId END ORDER BY CityName
END
As John Galt mentions in his answer , you should probably instead use df.to_dict('records')
. It's faster than transposing manually.
In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop
In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop
Use df.T.to_dict().values()
, like below:
In [1]: df
Out[1]:
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
repositories {
mavenCentral()
}
I added this in build.gradle, and it worked.
You have to add your jquery script to your chrome-extension project and to the background
section of your manifest.json like this :
"background":
{
"scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]
}
If you need jquery in a content_scripts, you have to add it in the manifest too:
"content_scripts":
[
{
"matches":["http://website*"],
"js":["thirdParty/jquery.1.10.2.min.js", "script.js"],
"css": ["css/style.css"],
"run_at": "document_end"
}
]
This is what I did.
Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions
.
Using #!/usr/bin/env NAME
makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.
You don't put a component in directives
You register it in @NgModule
declarations:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyChildComponent ],
bootstrap: [ App ]
})
and then You just put it in the Parent's Template HTML as : <my-child></my-child>
That's it.
For picking just one element of a generator use break
in a for
statement, or list(itertools.islice(gen, 1))
According to your example (literally) you can do something like:
while True:
...
if something:
for my_element in myfunct():
dostuff(my_element)
break
else:
do_generator_empty()
If you want "get just one element from the [once generated] generator whenever I like" (I suppose 50% thats the original intention, and the most common intention) then:
gen = myfunct()
while True:
...
if something:
for my_element in gen:
dostuff(my_element)
break
else:
do_generator_empty()
This way explicit use of generator.next()
can be avoided, and end-of-input handling doesn't require (cryptic) StopIteration
exception handling or extra default value comparisons.
The else:
of for
statement section is only needed if you want do something special in case of end-of-generator.
next()
/ .next()
:In Python3 the .next()
method was renamed to .__next__()
for good reason: its considered low-level (PEP 3114). Before Python 2.6 the builtin function next()
did not exist. And it was even discussed to move next()
to the operator
module (which would have been wise), because of its rare need and questionable inflation of builtin names.
Using next()
without default is still very low-level practice - throwing the cryptic StopIteration
like a bolt out of the blue in normal application code openly. And using next()
with default sentinel - which best should be the only option for a next()
directly in builtins
- is limited and often gives reason to odd non-pythonic logic/readablity.
Bottom line: Using next() should be very rare - like using functions of operator
module. Using for x in iterator
, islice
, list(iterator)
and other functions accepting an iterator seamlessly is the natural way of using iterators on application level - and quite always possible. next()
is low-level, an extra concept, unobvious - as the question of this thread shows. While e.g. using break
in for
is conventional.
Instead of bar
use self.bar
or Foo.bar
. Assigning to Foo.bar
will create a static variable, and assigning to self.bar
will create an instance variable.
The newest version of docker (18.03) offers a built in port forwarding solution. Inside your docker container simply have the db host set to host.docker.internal
. This will be forwarded to the host the docker container is running on.
Documentation for this is here: https://docs.docker.com/docker-for-mac/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
You need INDIRECT
function:
=INDIRECT("'"&A5&"'!G7")
Here's a function that is also based on cloneNode
, but with an option to clone only the parent node and move all the children (to preserve their event listeners):
function recreateNode(el, withChildren) {
if (withChildren) {
el.parentNode.replaceChild(el.cloneNode(true), el);
}
else {
var newEl = el.cloneNode(false);
while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
el.parentNode.replaceChild(newEl, el);
}
}
Remove event listeners on one element:
recreateNode(document.getElementById("btn"));
Remove event listeners on an element and all of its children:
recreateNode(document.getElementById("list"), true);
If you need to keep the object itself and therefore can't use cloneNode
, then you have to wrap the addEventListener
function and track the listener list by yourself, like in this answer.
Instead of images i choose background option:
HTML:
<div class="class1">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class2">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
<div class="class3">
<p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph,
</p>
</div>
CSS:
.class1 {
background: url("Some.png") no-repeat top center;
text-align: center;
}
.class2 {
background: url("Some2.png") no-repeat top center;
text-align: center;
}
.class3 {
background: url("Some3.png") no-repeat top center;
text-align: center;
}
The Spinner should fire an "OnItemSelected" event when something is selected:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
In management studio:
Properties
, then Options
.Tasks
-> Shrink
-> Files
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
It depends what you want to build really. For example the navigation drawer
uses fragments. Tabs use fragments
as well. Another good implementation,is where you have a listview
. When you rotate the phone and click a row the activity is shown in the remaining half of the screen. Personally,I use fragments
and fragment dialogs
,as it is more professional. Plus they are handled easier in rotation.
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password@sid @tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
Simple way to deal with merging single array values.
var values[0] = {"id":1235,"name":"value 1"}
values[1] = {"id":4323,"name":"value 2"}
var object=null;
var first=values[0];
for (var i in values)
if(i>0)
object= $.merge(values[i],first)
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
If mipadi's suggestion doesn't work, add this to config/environment.rb
# force Rails into production mode when
# you don't control web/app server and can't set it the proper way
ENV['RAILS_ENV'] ||= 'production'
Since the answer by @axtavt focuses on JPA
not spring-data-jpa
To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER
Spring-data-jpa
supports update operation.
You have to define the method in Repository interface.and annotated it with @Query
and @Modifying
.
@Modifying
@Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
void setUserInfoById(String firstname, String lastname, Integer userId);
@Query
is for defining custom query and @Modifying
is for telling spring-data-jpa
that this query is an update operation and it requires executeUpdate()
not executeQuery()
.
You can specify other return types:
int
- the number of records being updated.
boolean
- true if there is a record being updated. Otherwise, false.
Note: Run this code in a Transaction.
To use the java -jar selenium-server-standalone-2.45.0.jar
command-line tool you need to install a JDK.
You need to download and install the JDK and the standalone selenium server.
I simple gave below in all my browsers. I got image IIS7
http://localhost/
It is because you're only creating two td
elements and 2 text nodes.
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
Since recently, navigator.onLine
shows the same on all major browsers, and is thus useable.
if (navigator.onLine) {
// do things that need connection
} else {
// do things that don't need connection
}
The oldest versions that support this in the right way are: Firefox 41, IE 9, Chrome 14 and Safari 5.
Currently this will represent almost the whole spectrum of users, but you should always check what the users of your page have of capabilities.
Previous to FF 41, it would only show false
if the user put the browser manually in offline mode. In IE 8, the property was on the body
, instead of window
.
source: caniuse
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
You can add the script tags like how we use in the asp.net while doing client side validations like below.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
//Your code
});
</script>
Set navigation's modalPresentationStyle
to UIModalPresentationCustom
and set your presented view controller's background color as clear color.
Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.
TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat
For putting a whole pdf in your file and not just 1 page, use:
\usepackage{pdfpages}
\includepdf[pages=-]{myfile.pdf}
Edit 2018-05-28 I have changed the example to use Java 8's Time API:
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:
const alphaToHex = (alpha => {_x000D_
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
throw new Error('The argument must be a number between 0 and 1');_x000D_
}_x000D_
return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place
def moon(self, moon_name):
self.MName = moon_name
#but here cls method its use is different
@classmethod
def moon(cls, moon_name):
instance = cls()
instance.MName = moon_name
Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.
For practical programming approach :
While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .
ECMAScript 6 UPDATE
This uses a new feature of JavaScript called Promises
functionOne().then(functionTwo);
I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.
This worked for me:
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]
Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.
If you define the field as VARCHAR2(11 BYTE)
, Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.
By defining the field as VARCHAR2(11 CHAR)
you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.
I managed to get it to work by adding both the height
and min-height
properties to the CSS class.
The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:
.flex-container {
display: flex;
flex-direction: column;
min-height: 100px;
height: 100px;
}
Hope this helps!
Not tested but you can give a try. Tested and working. I hope you can play with AutoSizeMode
of DataGridViewColum
to achieve what you need.
Try setting
dataGridView1.DataSource = yourdatasource;<--set datasource before you set AutoSizeMode
//Set the following properties after setting datasource
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
This should work
I'm not up on my PowerShell syntax, but I think you could just call System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion(). This will return the version as a string (something like v2.0.50727
, I think).
I think it's the boundary (i.e. character following) of the last match or the beginning or end of the string.
You could put \s*
inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s
It's long but you could build the string dynamically of course.
You can see it working here: http://www.rubular.com/r/zzWwvppSpE
Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:
from xml.etree import ElementTree as ET
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
print(dict(zip(headers, values)))
same output as Sven Marnach's answer...
Here's how I would re-align my uiviews to get your solution:
I created a thumb rule of my own. Whenever you have to hide / show any uiview whose constraints might be affected, add all the affected / dependent subviews inside a uiview and update its leading / trailing / top / bottom constraint constant programmatically.
I think you can go with JWT (Json Web Tokens).
First you need to install the package System.IdentityModel.Tokens.Jwt:
$ dotnet add package System.IdentityModel.Tokens.Jwt
You will need to add a controller for token generation and authentication like this one:
public class TokenController : Controller
{
[Route("/token")]
[HttpPost]
public IActionResult Create(string username, string password)
{
if (IsValidUserAndPasswordCombination(username, password))
return new ObjectResult(GenerateToken(username));
return BadRequest();
}
private bool IsValidUserAndPasswordCombination(string username, string password)
{
return !string.IsNullOrEmpty(username) && username == password;
}
private string GenerateToken(string username)
{
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
};
var token = new JwtSecurityToken(
new JwtHeader(new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
After that update Startup.cs class to look like below:
namespace WebAPISecurity
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtBearerOptions =>
{
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
ValidateIssuer = false,
//ValidIssuer = "The name of the issuer",
ValidateAudience = false,
//ValidAudience = "The name of the audience",
ValidateLifetime = true, //validate the expiration and not before values in the token
ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
And that's it, what is left now is to put [Authorize]
attribute on the Controllers or Actions you want.
Here is a link of a complete straight forward tutorial.
http://www.blinkingcaret.com/2017/09/06/secure-web-api-in-asp-net-core/
function readFromRegistry (strRegistryKey, strDefault )
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )
if err.number <> 0 then
readFromRegistry= strDefault
else
readFromRegistry=value
end if
set WSHShell = nothing
end function
Usage :
str = readfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
wscript.echo "returned " & str
I tried all of the answers in this thread, and none of them worked for me -- not the snap files, not moving the projects, none of them.
What did work, oddly, was moving all projects and the .metadata folder somewhere else, starting Eclipse, closing it, and then moving them all back.
I get very different results on my system, but this is not using the defaults. You are likely bottlenecked on innodb-log-file-size, which is 5M by default. At innodb-log-file-size=100M I get results like this (all numbers are in seconds):
MyISAM InnoDB
create table 0.001 0.276
create 1024000 rows 2.441 2.228
insert test data 13.717 21.577
select 1023751 rows 2.958 2.394
fetch 1023751 batches 0.043 0.038
drop table 0.132 0.305
Increasing the innodb-log-file-size
will speed this up by a few seconds. Dropping the durability guarantees by setting innodb-flush-log-at-trx-commit=2
or 0
will improve the insert numbers somewhat as well.
Just add the line below to the <TextInput>
secureTextEntry={true}
You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:
root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}
#we capture release hash
$curr_os = $os['release']
case $curr_os['major'] {
'7': { .... something }
*: {something}
}
That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.
The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.
SELECT DATE_FORMAT(somedate, "%d/%m/%Y") AS formatted_date
..........
ORDER BY formatted_date DESC
The important concept is that you are evaluating an expression in your Razor code. The best way to do this (if, for example, you are in a foreach loop) is using a generic method.
The syntax for calling a generic method in Razor is:
@(expression)
In this case, the expression is:
User.Identity.IsAuthenticated ? "auth" : "anon"
Therefore, the solution is:
@(User.Identity.IsAuthenticated ? "auth" : "anon")
This code can be used anywhere in Razor, not just for an html attribute.
See @Kyralessa 's comment for C# Razor Syntax Quick Reference (Phil Haack's blog).
Jawn is a very flexible JSON parser library in Scala. It also allows generation of custom ASTs; you just need to supply it with a small trait to map to the AST.
Worked great for a recent project that needed a little bit of JSON parsing.
It's not as simple as just omitting the return
keyword. In Scala, if there is no return
then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return
keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.
An example:
def f() = {
if (something)
"A"
else
"B"
}
Here the last expression of the function f
is an if/else expression that evaluates to a String. Since there is no explicit return
marked, Scala will infer that you wanted to return the result of this if/else expression: a String.
Now, if we add something after the if/else expression:
def f() = {
if (something)
"A"
else
"B"
if (somethingElse)
1
else
2
}
Now the last expression is an if/else expression that evaluates to an Int. So the return type of f
will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.
Finally, we can avoid the return
keyword even with a nested if-else expression like yours:
def f() = {
if(somethingFirst) {
if (something) // Last expression of `if` returns a String
"A"
else
"B"
}
else {
if (somethingElse)
1
else
2
"C" // Last expression of `else` returns a String
}
}
if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool
Hope it saved your time
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
I know this has already been answered, but I just spent more time than I care to admit coming up with single-line SQL statements to accomplish this, so I'll share them here in case anyone else needs to do the same:
-- Encode the string "TestData" in Base64 to get "VGVzdERhdGE="
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'VARCHAR(MAX)'
) Base64Encoding
FROM (
SELECT CAST('TestData' AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;
-- Decode the Base64-encoded string "VGVzdERhdGE=" to get back "TestData"
SELECT
CAST(
CAST(N'' AS XML).value(
'xs:base64Binary("VGVzdERhdGE=")'
, 'VARBINARY(MAX)'
)
AS VARCHAR(MAX)
) ASCIIEncoding
;
I had to use a subquery-generated table in the first (encoding) query because I couldn't find any way to convert the original value ("TestData") to its hex string representation ("5465737444617461") to include as the argument to xs:hexBinary() in the XQuery statement.
I hope this helps someone!
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory,
ApplicationDbContext context)
{
context.Database.Migrate();
...
For completeness, I'm posting a version of the toMapOfNullables with a mergeFunction param:
public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) {
return Collectors.collectingAndThen(Collectors.toList(), list -> {
Map<K, U> result = new HashMap<>();
for(T item : list) {
K key = keyMapper.apply(item);
U newValue = valueMapper.apply(item);
U value = result.containsKey(key) ? mergeFunction.apply(result.get(key), newValue) : newValue;
result.put(key, value);
}
return result;
});
}
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
You have a scope problem. Define the struct before the function, not inside it.
You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
console.log(guest);_x000D_
});
_x000D_
Example:
renderPayments(noGuest) {
return Array(noGuest).fill(noGuest).map((guess, index) => {
return(
<View key={index}>
<View><TextInput /></View>
<View><TextInput /></View>
<View><TextInput /></View>
</View>
);
}
}
Then use it where you want it
render() {
return(
const { guest } = this.state;
...
{this.renderPayments(guest)}
);
}
Hope you got the idea.
If you want to understand this in simple Javascript check Array.prototype.fill()
If you really want to retrieve classes you make with a string, you should store (or properly worded, reference) them in a dictionary. After all, that'll also allow to name your classes in a higher level and avoid exposing unwanted classes.
Example, from a game where actor classes are defined in Python and you want to avoid other general classes to be reached by user input.
Another approach (like in the example below) would to make an entire new class, that holds the dict
above. This would:
Example:
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
def __getitem__(self, n):
return self.classes[n]
class Foo:
def __init__(self):
self.a = 0
def bar(self):
return self.a + 1
class Spam(Foo):
def __init__(self):
self.a = 2
def bar(self):
return self.a + 4
class SomethingDifferent:
def __init__(self):
self.a = "Hello"
def add_world(self):
self.a += " World"
def add_word(self, w):
self.a += " " + w
def finish(self):
self.a += "!"
return self.a
aclasses = ClassHolder()
dclasses = ClassHolder()
aclasses.add_class(Foo)
aclasses.add_class(Spam)
dclasses.add_class(SomethingDifferent)
print aclasses
print dclasses
print "======="
print "o"
print aclasses["Foo"]
print aclasses["Spam"]
print "o"
print dclasses["SomethingDifferent"]
print "======="
g = dclasses["SomethingDifferent"]()
g.add_world()
print g.finish()
print "======="
s = []
s.append(aclasses["Foo"]())
s.append(aclasses["Spam"]())
for a in s:
print a.a
print a.bar()
print "--"
print "Done experiment!"
This returns me:
<__main__.ClassHolder object at 0x02D9EEF0>
<__main__.ClassHolder object at 0x02D9EF30>
=======
o
<class '__main__.Foo'>
<class '__main__.Spam'>
o
<class '__main__.SomethingDifferent'>
=======
Hello World!
=======
0
1
--
2
6
--
Done experiment!
Another fun experiment to do with those is to add a method that pickles the ClassHolder
so you never lose all the classes you did :^)
UPDATE: It is also possible to use a decorator as a shorthand.
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
# -- the decorator
def held(self, c):
self.add_class(c)
# Decorators have to return the function/class passed (or a modified variant thereof), however I'd rather do this separately than retroactively change add_class, so.
# "held" is more succint, anyway.
return c
def __getitem__(self, n):
return self.classes[n]
food_types = ClassHolder()
@food_types.held
class bacon:
taste = "salty"
@food_types.held
class chocolate:
taste = "sweet"
@food_types.held
class tee:
taste = "bitter" # coffee, ftw ;)
@food_types.held
class lemon:
taste = "sour"
print(food_types['bacon'].taste) # No manual add_class needed! :D
This works for me, found this in the O'Reilly's "Mastering Regular Expressions":
/^\w+$/
Explanation:
Verify yourself:
const regex = /^\w+$/;_x000D_
const str = `nut_cracker_12`;_x000D_
let m;_x000D_
_x000D_
if ((m = regex.exec(str)) !== null) {_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
1) in a query window in SQL Server Management Studio, run the command:
SET SHOWPLAN_ALL ON
2) run your slow query
3) your query will not run, but the execution plan will be returned. store this output
4) run your fast version of the query
5) your query will not run, but the execution plan will be returned. store this output
6) compare the slow query version output to the fast query version output.
7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.
Well, I totally agree with answers already exist on this point:
bootstrap.yml
is used to save parameters that point out where the remote configuration is and Bootstrap Application Context is created with these remote configuration.Actually, it is also able to store normal properties just the same as what application.yml
do. But pay attention on this tricky thing:
bootstrap.yml
, they will get lower precedence than almost any other property sources, including application.yml. As described here.Let's make it clear, there are two kinds of properties related to bootstrap.yml
:
bootstrap.yml
to find the properties holder (A file system, git repository or something else), and the properties we get in this way are with high precedence, so they cannot be overridden by local configuration. As described here.bootstrap.yml
. As explained early, they will get lower precedence. Use them to set defaults maybe a good idea.So the differences between putting a property on application.yml
or bootstrap.yml
in spring boot are:
bootstrap.yml
.application.yml
will get higher precedence.This is because the inline style display:block
is overwriting your CSS. You'll need to either remove this inline style or use:
#tfl {
display: none !important;
}
This overrides inline styles. Note that using !important
is generally not recommended unless it's a last resort.
Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray
. You can check the dimensionality of a numpy array using the .ndim
property. The .shape
property is a tuple of length .ndim
containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.
If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:
command|head -n 6|tail -n 1|awk '{print $4}'
A simple example, similar to the solutions above. This doesn't require monitoring any process output. The next example uses tail to follow output.
$ echo '#!/bin/bash' > tmp.sh
$ echo 'sleep 30; exit 5' >> tmp.sh
$ chmod +x tmp.sh
$ ./tmp.sh &
[1] 7454
$ pid=$!
$ wait $pid
[1]+ Exit 5 ./tmp.sh
$ echo $?
5
Use tail to follow process output and quit when the process is complete.
$ echo '#!/bin/bash' > tmp.sh
$ echo 'i=0; while let "$i < 10"; do sleep 5; echo "$i"; let i=$i+1; done; exit 5;' >> tmp.sh
$ chmod +x tmp.sh
$ ./tmp.sh
0
1
2
^C
$ ./tmp.sh > /tmp/tmp.log 2>&1 &
[1] 7673
$ pid=$!
$ tail -f --pid $pid /tmp/tmp.log
0
1
2
3
4
5
6
7
8
9
[1]+ Exit 5 ./tmp.sh > /tmp/tmp.log 2>&1
$ wait $pid
$ echo $?
5
You also need to replace your indexes:
class RenameOldTableToNewTable< ActiveRecord:Migration
def self.up
remove_index :old_table_name, :column_name
rename_table :old_table_name, :new_table_name
add_index :new_table_name, :column_name
end
def self.down
remove_index :new_table_name, :column_name
rename_table :new_table_name, :old_table_name
add_index :old_table_name, :column_name
end
end
And rename your files etc, manually as other answers here describe.
See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.
Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.
And finally, doing this without a regression test suite would be nuts.
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
For those who don't want any plugin or other stuffs, We can use the document.styleSheets to disable/enable the css.
// code to disable all the css
for (const item in document.styleSheets) {
document.styleSheets[item].disabled=true;
}
If you use chrome, you can create a function and add to your snippets. So that you can use the console to enable/disable the css for any sites.
// Snippets -> DisableCSS
function disableCss(value = true){
for (const item in document.styleSheets) {
document.styleSheets[item].disabled=value;
}
}
// in console
disableCss() // by default is disable
disableCss(false) // to enable
This worked for me:
export _JAVA_OPTIONS="-Xmx1g"
It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:
java -XshowSettings:vm
and it will tell you:
Picked up _JAVA_OPTIONS: -Xmx1g
You can use a powershell script (this works for users with folder redirection as well to not have their recycle bins take up server storage space)
$Shell = New-Object -ComObject Shell.Application
$RecBin = $Shell.Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
The above script is taken from here.
If you have windows 10 and powershell 5 there is the Clear-RecycleBin
commandlet.
To use Clear-RecycleBin
inside PowerShell without confirmation, you can use Clear-RecycleBin -Force
. Official documentation can be found here
The answer is that #1 is technically correct based on the real meaning of the Mega prefix, however (and in life there is always a however) the math for that doesn't come out so nice in base 2, which is how computers count, so #2 is what people really use.
This is the query I normally use,
select s.sid
,s.serial#
,s.username
,s.machine
,s.status
,s.lockwait
,t.used_ublk
,t.used_urec
,t.start_time
from v$transaction t
inner join v$session s on t.addr = s.taddr;
What if one of the values is negative? Wouldn't a better idea be:
double NextDouble(double min, double max)
{
if (min >= max)
throw new ArgumentOutOfRangeException();
return random.NextDouble() * (Math.Abs(max-min)) + min;
}
This is a slight modification to the earlier answers...
There is no need for $parse
angular.directive('input', [function () {
'use strict';
var directiveDefinitionObject = {
restrict: 'E',
require: '?ngModel',
link: function postLink(scope, iElement, iAttrs, ngModelController) {
if (iAttrs.value && ngModelController) {
ngModelController.$setViewValue(iAttrs.value);
}
}
};
return directiveDefinitionObject;
}]);
Create file ~/.mavenrc
then paste this into the file
export JAVA_HOME=$(/usr/libexec/java_home)
test
mvn -v
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);
In Servlets you have 4 scopes where you can store data.
Make sure you understand these. For more look here
In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.
In HTML 5, the type attribute is optional and defaults to text/javascript
Use <script type="text/javascript">
or simply <script>
(if omitted, the type is the same). Do not use <script language="JavaScript">
; the language attribute is deprecated
Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?
Do you need type attribute at all?
I am using HTML5- No
I am not using HTML5 - Yes
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray)
. I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc
function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
... etc.
After that.
json_encode($associativeArray);
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
For example, given an input:
http://google.com/resource?key=value
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue
So:
C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;
public class URLEncodeSample {
public static void main( String [] args ) throws Throwable {
System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
}
}
C:\oreyes\samples\java\URL>javac URLEncodeSample.java
C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
As expected.
What would be the problem with this?
Declare an array of strings in C++ like this : char array_of_strings[][]
For example : char array_of_strings[200][8192];
will hold 200 strings, each string having the size 8kb or 8192 bytes.
use strcpy(line[i],tempBuffer);
to put data in the array of strings.
As noted in comments above, while still on some UA implementations, readAsBinaryString
method didn't made its way to the specs and should not be used in production.
Instead, use readAsArrayBuffer
and loop through it's buffer
to get back the binary string :
document.querySelector('input').addEventListener('change', function() {_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function() {_x000D_
_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
_x000D_
}, false);
_x000D_
<input type="file" />_x000D_
<div id="result"></div>
_x000D_
For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.
Yes, the file API does provide a way to convert your File, in the <input type="file"/>
to a binary string, thanks to the FileReader Object and its method readAsBinaryString
.
[But don't use it in production !]
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var binaryString = this.result;_x000D_
document.querySelector('#result').innerHTML = binaryString;_x000D_
}_x000D_
reader.readAsBinaryString(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
If you want an array buffer, then you can use the readAsArrayBuffer()
method :
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result;_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
why do that to yourself?
jQuery:
$("#element").fadeOut();
$("#element").fadeIn();
I think that's easier.
Yes, you absolutely can do this. For example:
public class PersonComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
// Assume no nulls, and simple ordinal comparisons
// First by campus - stop if this gives a result.
int campusResult = p1.getCampus().compareTo(p2.getCampus());
if (campusResult != 0)
{
return campusResult;
}
// Next by faculty
int facultyResult = p1.getFaculty().compareTo(p2.getFaculty());
if (facultyResult != 0)
{
return facultyResult;
}
// Finally by building
return p1.getBuilding().compareTo(p2.getBuilding());
}
}
Basically you're saying, "If I can tell which one comes first just by looking at the campus (before they come from different campuses, and the campus is the most important field) then I'll just return that result. Otherwise, I'll continue on to compare faculties. Again, stop if that's enough to tell them apart. Otherwise, (if the campus and faculty are the same for both people) just use the result of comparing them by building."
It is a little late but it might help someone. I created a procedure sometimes back which does the following using T-SQL:
I have listed it on my blog here
I could not post a reply on Paul's comment so I am creating new comment for Vidhya here:
Wrapper will be a SuperClass
for the two classes which we want to store as a value.
and inside wrapper class, we can put the associations as the instance variable objects for the two class objects.
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
and in HashMap we can put in this way,
Map<KeyObject, WrapperObject>
WrapperObj will have class variables: class1Obj, class2Obj
Find timestamp from DateTime:
private long ConvertToTimestamp(DateTime value)
{
TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
TimeZone localZone = TimeZone.CurrentTimeZone;
System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (NyTime - epoch);
return (long)Convert.ToDouble(span.TotalSeconds);
}
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.