This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.
split
slice
concentrate
This is a good workout for beginners and it's easy to achieve.
Another advanced method is a function like this:
def trim(s):
return trim(s[slice])
And for this question, you just want to remove the last characters, so you can write like this:
def trim(s):
return s[ : -3]
I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!
If you want to remove some specific characters, you can add some if judgements:
def trim(s):
if [conditions]: ### for some cases, I recommend using isinstance().
return trim(s[slice])
simply do this..
@Override
public void onBackPressed() {
//super.onBackPressed();
}
commenting out the //super.onBackPressed(); will do the trick
you may try this one, used CONCAT
WHERE LastName LIKE Concat('%',@LastName,'%')
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
1.Pure batch solution that (ab)uses XCOPY
command and its /P /L
switches found here (some improvements on this could be found here ):
:: Hidden.cmd
::Tom Lavedas, 02/05/2013, 02/20/2013
::Carlos, 02/22/2013
::https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/f7mb_f99lYI
@Echo Off
:HInput
SetLocal EnableExtensions EnableDelayedExpansion
Set "FILE=%Temp%.\T"
Set "FILE=.\T"
Keys List >"%File%"
Set /P "=Hidden text ending with Ctrl-C?: " <Nul
Echo.
Set "HInput="
:HInput_
For /F "tokens=1* delims=?" %%A In (
'"Xcopy /P /L "%FILE%" "%FILE%" 2>Nul"'
) Do (
Set "Text=%%B"
If Defined Text (
Set "Char=!Text:~1,1!"
Set "Intro=1"
For /F delims^=^ eol^= %%Z in ("!Char!") Do Set "Intro=0"
Rem If press Intro
If 1 Equ !Intro! Goto :HInput#
Set "HInput=!HInput!!Char!"
)
)
Goto :HInput_
:HInput#
Echo(!HInput!
Goto :Eof
1.2 Another way based on replace command
@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set /P "=Enter a Password:" < Nul
Call :PasswordInput
Echo(Your input was:!Line!
Goto :Eof
:PasswordInput
::Author: Carlos Montiers Aguilera
::Last updated: 20150401. Created: 20150401.
::Set in variable Line a input password
For /F skip^=1^ delims^=^ eol^= %%# in (
'"Echo(|Replace.exe "%~f0" . /U /W"') Do Set "CR=%%#"
For /F %%# In (
'"Prompt $H &For %%_ In (_) Do Rem"') Do Set "BS=%%#"
Set "Line="
:_PasswordInput_Kbd
Set "CHR=" & For /F skip^=1^ delims^=^ eol^= %%# in (
'Replace.exe "%~f0" . /U /W') Do Set "CHR=%%#"
If !CHR!==!CR! Echo(&Goto :Eof
If !CHR!==!BS! (If Defined Line (Set /P "=!BS! !BS!" <Nul
Set "Line=!Line:~0,-1!"
)
) Else (Set /P "=*" <Nul
If !CHR!==! (Set "Line=!Line!^!"
) Else Set "Line=!Line!!CHR!"
)
Goto :_PasswordInput_Kbd
2.Password submitter that uses a HTA pop-up . This is a hybrit .bat/jscript/mshta file and should be saved as a .bat:
<!-- :
:: PasswordSubmitter.bat
@echo off
for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
set "pass=%%p"
)
echo your password is %pass%
exit /b
-->
<html>
<head><title>Password submitter</title></head>
<body>
<script language='javascript' >
window.resizeTo(300,150);
function entperPressed(e){
if (e.keyCode == 13) {
pipePass();
}
}
function pipePass() {
var pass=document.getElementById('pass').value;
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
close(fso.Write(pass));
}
</script>
<input type='password' name='pass' size='15' onkeypress="return entperPressed(event)" ></input>
<hr>
<button onclick='pipePass()'>Submit</button>
</body>
</html>
3.A self-compiled .net hybrid .Again should be saved as .bat
.In difference with other solutions it will create/compile a small .exe file that will be called (if you wish you can delete it). Also requires installed .net framework but that's rather not a problem:
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal enableDelayedExpansion
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
for /f "tokens=* delims=" %%p in ('"%~n0.exe"') do (
set "pass=%%p"
)
echo your password is !pass!
endlocal & exit /b %errorlevel%
*/
import System;
var pwd = "";
var key;
Console.Error.Write("Enter password: ");
do {
key = Console.ReadKey(true);
if ( (key.KeyChar.ToString().charCodeAt(0)) >= 20 && (key.KeyChar.ToString().charCodeAt(0) <= 126) ) {
pwd=pwd+(key.KeyChar.ToString());
Console.Error.Write("*");
}
if ( key.Key == ConsoleKey.Backspace && pwd.Length > 0 ) {
pwd=pwd.Remove(pwd.Length-1);
Console.Error.Write("\b \b");
}
} while (key.Key != ConsoleKey.Enter);
Console.Error.WriteLine();
Console.WriteLine(pwd);
// Used In TypeScript For Angular 4+
const viewArray = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
const arrayObj = any;
const objectData = any;
for (let index = 0; index < this.viewArray.length; index++) {
this.arrayObj = this.viewArray[index];
this.arrayObj.filter((x) => {
if (x.id === id) {
this.objectData = x;
}
});
console.log('Json Object Data by ID ==> ', this.objectData);
}
};
This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.
There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.
Hit replace all, and voila, all instances of '0'
will be replaced with '255'
.
Note: this feature is ONLY available when you use ? + option + F.
It does NOT appear when you use ? + shift + F.
Note: this will replace all instances of '0'
with '255'
. If you wanted to replace 0
(without the quotes) with 255
, then just put 0
(without quotes) and 255
in the Find What:
and Replace With:
fields respectively.
Note:
option key is also labeled as the alt key.
? key is also labeled as the command key.
this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.
PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {}
}));
System.out.println("It will not print");
//To again enable it.
System.setOut(ps);
System.out.println("It will print");
You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:
WITH group1 AS (
SELECT testA
FROM tableA
),
group2 AS (
SELECT testB
FROM tableB
)
SELECT *
FROM group1
JOIN group2 ON group1.testA = group2.testB --your choice of join
;
You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select icon <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li><span class="glyphicon glyphicon-cutlery"></span></li>
<li><span class="glyphicon glyphicon-fire"></span></li>
<li><span class="glyphicon glyphicon-glass"></span></li>
<li><span class="glyphicon glyphicon-heart"></span></li>
</ul>
</div>
I'm using Angular.js so this is the actual code I used:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Avatar <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
<span ng-class="getAvatar(avatar)"></span>
</li>
</ul>
</div>
And in my controller:
$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];
$scope.getAvatar=function(avatar){
return 'glyphicon glyphicon-'+avatar;
};
I also had this problem. In my case it was because of no grants were assigned to MySQL user. Assigning grants to MySQL user which my app uses resolved the issue:
grant select, insert, delete, update on my_db.* to 'my_user'@'%';
[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
On Ubuntu system, I purged the PostgreSQL and re-installed it. All the databases are restored. This solved the problem for me.
Advice - Take the backup of the databases to be on the safer side.
Just simple as this
window.location.href='http://www.google.com/';
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath())
doesn't work for all paths! The path is still URL-encoded!)
Take note of what is printed for x
. You are trying to convert an array (basically just a list) into an int. length-1
would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.
EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize
is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?
import numpy as np
import matplotlib.pyplot as plt
import datetime
time_start = datetime.datetime.now()
# My original answer
def f(x):
rebuilt_to_plot = []
for num in x:
rebuilt_to_plot.append(np.int(num))
return rebuilt_to_plot
for t in range(10000):
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f(x))
time_end = datetime.datetime.now()
# Answer by ayhan
def f_1(x):
return np.int(x)
for t in range(10000):
f2 = np.vectorize(f_1)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
time_end_2 = datetime.datetime.now()
print time_end - time_start
print time_end_2 - time_end
As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.
import java.util.*;
public class Genric<E>
{
public static void main(String[] args)
{
Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
if(unique.get(string) == null)
unique.put(string, 1);
else
unique.put(string, unique.get(string) + 1);
}
String uniqueString = join(unique.keySet(), ", ");
List<Integer> value = new ArrayList<Integer>(unique.values());
System.out.println("Output = " + uniqueString);
System.out.println("Values = " + value);
}
public static String join(Collection<String> s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator<String> iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
}
New String is Output = House, Dog
Int array (or rather list) Values = [3, 4]
(you can use List::toArray) for getting an array.
You could use a more generic converter
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}
And in the XAML-Part you use:
<Grid>
<Grid.Resources>
<l:EnumBooleanConverter x:Key="enumBooleanConverter" />
</Grid.Resources>
<StackPanel >
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
</StackPanel>
</Grid>
This is a list of available colours (both background and foreground) in the console with some available actions (like reset, reverse, etc).
const colours = {
reset: "\x1b[0m",
bright: "\x1b[1m",
dim: "\x1b[2m",
underscore: "\x1b[4m",
blink: "\x1b[5m",
reverse: "\x1b[7m",
hidden: "\x1b[8m",
fg: {
black: "\x1b[30m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
white: "\x1b[37m",
crimson: "\x1b[38m" // Scarlet
},
bg: {
black: "\x1b[40m",
red: "\x1b[41m",
green: "\x1b[42m",
yellow: "\x1b[43m",
blue: "\x1b[44m",
magenta: "\x1b[45m",
cyan: "\x1b[46m",
white: "\x1b[47m",
crimson: "\x1b[48m"
}
};
Here's an example of how to use it:
console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ;
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.
Or you can install some utility modules:
npm install console-info console-warn console-error --save-dev
These modules will show something like the following to the console when you use them:
In your case you have a List
of Strings and most of the already proposed solutions (I specially like @guyblank answer) are just fine but!!!, if you have a List
of beans, which is my case, you can use Comparable
interface in your bean like this:
public class UserBean implements Comparable<UserBean> {
private String name;
private String surname;
private Integer phone;
// GETTERS AND SETTERS
public int compareTo(UserBean bean) {
return name.compareToIgnoreCase(bean.name);
}
}
Then you only need to create your ArrayList<UserBean> userBeanArray = new ArrayList<UserBean>();
, fill it and sort it: Collections.sort(userBeanArray);
And you have it done!
Hope to help to community ;-)
Another way to get around this is just to upgrade your application to ELMAH 1.2 rather than 1.1.
With Java 8, you can do this.
final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();
I use nice set of useful filter library "Angular-filter" and one of them called "truncate" is useful too.
https://github.com/a8m/angular-filter#truncate
usage is:
text | truncate: [length]: [suffix]: [preserve-boolean]
dialog.setCanceledOnTouchOutside(true);
to close dialog on touch outside.
And if you don't want to close on touch outside, use the code below:
dialog.setCanceledOnTouchOutside(false);
There are a lot of things in C that aren't technically needed because they can be more or less easily implemented in terms of other things. Here is an incomplete list:
Imagine what your code would look like without these and you may find your answer. The ternary operator is a form of "syntactic sugar" that if used with care and skill makes writing and understanding code easier.
This error can occur if you are using a software update server which doesn't host the required package.
You can check this by running
defaults read /Library/Preferences/com.apple.SoftwareUpdate
and seeing if you have an entry called CatalogURL or AppleCatalogURL
You can point back at the Apple software update server by either removing this entry or using the command
sudo softwareupdate --clear-catalog
And then run the command line tools install again.
One reason is that it is easy to create a set from map:
s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element
delete(s, 2) // remove element
Union
s_union := map[int]bool{}
for k, _ := range s1{
s_union[k] = true
}
for k, _ := range s2{
s_union[k] = true
}
Intersection
s_intersection := map[int]bool{}
for k,_ := range s1 {
if s2[k] {
s_intersection[k] = true
}
}
It is not really that hard to implement all other set operations.
Try this:
var req={StrContactDetails:'data',IsPrimary:'True'}
$.ajax({
type: 'POST',
data: req,
url: '@url.Action("SaveEmergencyContact","Dhp")',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(req),
success: function (data) {
alert("Success");
},
error: function (ob, errStr) {
alert("An error occured.Please try after sometime.");
}
});
Easiest way is using laravel toArray function itself:
$result = array_map(function ($value) {
return $value instanceof Arrayable ? $value->toArray() : $value;
}, $result);
public function convertToUtf8($text) {
if(!$this->html)
$this->html = cURL('http://'.$this->url, array('timeout' => 15));
$html = $this->html;
preg_match('/<meta.*?charset=(|\")(.*?)("|\")/i', $html, $matches);
$charset = $matches[2];
if($charset)
return mb_convert_encoding($text, 'UTF-8', $charset);
else
return $text;
}
cURL default options:
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
I tried something like this. It helped me. If found on meta charset info, I'm converting, otherwise doing nothing.
Depending upon the relationships of the repositories, another approach is to add the other repository (repositories) as a git submodules to one of the repositories. A git submodule is creates a reference to the other repos. Those submodule repos are not cloned unless the you specify the --recursive
flag when cloning the "superproject" (official term).
Here's the command to add a submodule into the current project:
git submodule add <repository URI path to clone>
We are using Jenkins v1.645 and the git SCM will out-of-the-box do a recursive clone for superprojects. Voila you get the superproject files and all the dependent (submodule) repo files in their own respective directories in the same Jenkins job workspace.
Not vouching that this is the correct approach rather it's an approach.
A simple print statement with the variable name which contains the reference of the Hash Map would do :
HashMap<K,V> HM = new HashMap<>(); //empty
System.out.println(HM); //prints key value pairs enclosed in {}
This works because the toString()
method is already over-ridden in the AbstractMap class
which is extended by the HashMap Class
More information from the documentation
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).
This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.
DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
if (d == DialogResult.Yes)
{
//Contents
}
else if (d == DialogResult.No)
{
//Contents
}
Just call mkdir C:\VTS
no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.
My version (of course I could have used the built in walk in Java 8 ;-) ):
public static List<File> findFilesIn(File rootDir, Predicate<File> predicate) {
ArrayList<File> collected = new ArrayList<>();
walk(rootDir, predicate, collected);
return collected;
}
private static void walk(File dir, Predicate<File> filterFunction, List<File> collected) {
Stream.of(listOnlyWhenDirectory(dir))
.forEach(file -> walk(file, filterFunction, addAndReturn(collected, file, filterFunction)));
}
private static File[] listOnlyWhenDirectory(File dir) {
return dir.isDirectory() ? dir.listFiles() : new File[]{};
}
private static List<File> addAndReturn(List<File> files, File toAdd, Predicate<File> filterFunction) {
if (filterFunction.test(toAdd)) {
files.add(toAdd);
}
return files;
}
Look back to formal logic and algebra. An expression like
A & B & (D | E)
may be negated in a couple of ways:
The obvious way:
!( A & B & ( D | E ) )
The above can also be restated, you just need to remember some properties of logical expressions:
!( A & B )
is the equivalent of (!A | !B)
.!( A | B )
is the equivalent of (!A & !B)
.!( !A )
is the equivalent of (A).Distribute the NOT (!) across the entire expression to which it applies, inverting operators and eliminating double negatives as you go along:
!A | !B | ( !D & !E )
So, in general, any where clause may be negated according to the above rules. The negation of this
select *
from foo
where test-1
and test-2
and ( test-3
OR test-4
)
is
select *
from foo
where NOT( test-1
and test-2
and ( test-3
OR test-4
)
)
or
select *
from foo
where not test-1
OR not test-2
OR ( not test-3
and not test-4
)
Which is better? That's a very context-sensitive question. Only you can decide that.
Be aware, though, that the use of NOT can affect what the optimizer can or can't do. You might get a less than optimal query plan.
If you wish to automate scraping of large amount pages or data, then you could try Gotz ETL.
It is completely model driven like a real ETL tool. Data structure, task workflow and pages to scrape are defined with a set of XML definition files and no coding is required. Query can be written either using Selectors with JSoup or XPath with HtmlUnit.
timeout-decorator
don't work on windows system as , windows didn't support signal
well.
If you use timeout-decorator in windows system you will get the following
AttributeError: module 'signal' has no attribute 'SIGALRM'
Some suggested to use use_signals=False
but didn't worked for me.
Author @bitranox created the following package:
pip install https://github.com/bitranox/wrapt-timeout-decorator/archive/master.zip
Code Sample:
import time
from wrapt_timeout_decorator import *
@timeout(5)
def mytest(message):
print(message)
for i in range(1,10):
time.sleep(1)
print('{} seconds have passed'.format(i))
def main():
mytest('starting')
if __name__ == '__main__':
main()
Gives the following exception:
TimeoutError: Function mytest timed out after 5 seconds
Or
// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
Both answers pulled from JavaScript equivalent to printf/string.format
Do like this:
HTML
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
CSS
.parent{
width: 400px;
background: red;
}
.child{
float: left;
width:200px;
background:green;
height: 100px;
}
This is working jsfiddle. Change child width
to more then 200px
and they will stack.
The way to do it is with ternary operator:
name = city.getName() == null ? city.getName() : "N/A"
However, I believe you have a typo in your code above, and you mean to say:
if (city.getName() != null) ...
Converting them to timestamps is the way to go alright, using strtotime, e.g.
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$user_ts = strtotime($date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
Resize image with high quality:
private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {
try {
BufferedImage image = ImageIO.read(uploadedInputStream);
Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(originalImage, 0, 0, width, height, null);
g2d.dispose();
g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
// Something is going wrong while resizing image
return uploadedInputStream;
}
}
If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:
watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'
The only bad thing about the show [full] processlist
is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST
open possibilities to remove from the output anything you don't want to see:
SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G
Now we can use:
sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)
you can also do this
margin-top:-30px;
min-height:40px;
this "help" to stop the div yanking everything up a bit.
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.
"babel": {
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]}
Note: Don't forget to exit the console and reopen before executing the npm or yarn commands.
You could do something like
<a href="http://home.com"><img src="images/logo.png" alt="" id="logo"></a>
in HTML
You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.
If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.
each_with_object
is your friend!
input = [:bla,:blubb,:bleh,:bla,:bleh,:bla,:blubb,:brrr]
# to get the counts of the elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}
=> {:bla=>3, :blubb=>2, :bleh=>2, :brrr=>1}
# to get only the counts of the non-unique elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}.reject{|k,v| v < 2}
=> {:bla=>3, :blubb=>2, :bleh=>2}
System.Net.ServicePointManager.Expect100Continue = false;
This issue sometime occurs due the reason of proxy server implemented on web server. To bypass the proxy server by putting this line before calling the send service.
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axisView
classFrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
Java 8
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 45
System.out.println(LocalDateTime.now().getSecond()); // 32
Calendar
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
Joda Time
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 45
System.out.println(new DateTime().getSecondOfMinute()); // 32
Java 8
// 07:48:55.056
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
// 7:48:55
System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());
// 07:48:55
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
// 074855
System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));
// 07:48:55
System.out.println(new Date().toString().substring(11, 20));
To remove ALL containers:
sudo docker ps -a | grep -v CONTAINER | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm -f
Explanation:
sudo docker ps -a
Returns a list of containers.
awk '{print $1}'
Gets the first column which is the container ID.
grep -v CONTAINER
Remove the title.
The last pipe sends the IDs to sudo docker rm -f
safely.
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
Here are the few code snippet which can be used for framework which use Typescript, protractor, jasmine
browser.wait(until.visibilityOf(OversightAutomationOR.lblContentModal), 3000, "Modal text is present");
// Asserting a text
OversightAutomationOR.lblContentModal.getText().then(text => {
this.assertEquals(text.toString().trim(), AdminPanelData.lblContentModal);
});
// Asserting an element
expect(OnboardingFormsOR.masterFormActionCloneBtn.isDisplayed()).to.eventually.equal(true
);
OnboardingFormsOR.customFormActionViewBtn.isDisplayed().then((isDisplayed) => {
expect(isDisplayed).to.equal(true);
});
// Asserting a form
formInfoSection.getText().then((text) => {
const vendorInformationCount = text[0].split("\n");
let found = false;
for (let i = 0; i < vendorInformationCount.length; i++) {
if (vendorInformationCount[i] === customLabel) {
found = true;
};
};
expect(found).to.equal(true);
});
How about this:
$ seq 1 100000 | tail -n +10000 | head -n 10
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
It uses tail
to output from the 10,000th line and onwards and then head
to only keep 10 lines.
The same (almost) result with sed
:
$ seq 1 100000 | sed -n '10000,10010p'
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
This one has the advantage of allowing you to input the line range directly.
Just check this:
$(document).ready(function() {
$(".scroll").click(function(event){
$('html, body').animate({scrollTop: '+=150px'}, 800);
});
});
It will make scroller scroll from current position when your element is clicked
And 150px is used to scroll for 150px downwards
The built-in matrix
function has the nice option to enter data byrow
. Combine that with an unlist
on your source list will give you a matrix. We also need to specify the number of rows so it can break up the unlisted data. That is:
> matrix(unlist(a), byrow=TRUE, nrow=length(a) )
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
You can use lapply
to pass each column to str_length
, then cbind
it to your original data.frame
...
library(stringr)
out <- lapply( df , str_length )
df <- cbind( df , out )
# col1 col2 col1 col2
#1 abc adf qqwe 3 8
#2 abcd d 4 1
#3 a e 1 1
#4 abcdefg f 7 1
AFAIR, MySQL implements INTERSECT through INNER JOIN.
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
The best answer is to add a Resources/.gitignore file under Resources containing:
# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo
If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:
# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo
You will need to edit that pattern if you add directories deeper than specified.
In Program.cs, between:
static int Main(string[] agrs)
{
and the rest of your code, add:
#if DEBUG
int rtn = Main2(args);
Console.WriteLine("return " + rtn);
Console.WriteLine("ENTER to continue.");
Console.Read();
return rtn;
}
static int Main2(string[] args)
{
#endif
I just made my life simple:
CREATE VIEW another_table AS SELECT * FROM another_database.another_table;
hope it is helpful... cheers...
EDITED
You can look into sys.tables for checking existence desired table:
IF NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')
BEGIN
CREATE TABLE [SchemaName].[YourTable](
....
....
....
)
END
If I'm not mistaken, C# templates are determined at runtime. This must be slower than compile time templates of C++.
And when you take in all the other compile-time optimizations mentioned by so many others, as well as the lack of safety that does, indeed, mean more speed...
I'd say C++ is the obvious choice in terms of raw speed and minimum memory consumption. But this also translates into more time developing the code and ensuring you aren't leaking memory or causing any null pointer exceptions.
Verdict:
C#: Faster development, slower run
C++: Slow development, faster run.
Use:
git log --graph --abbrev-commit --decorate --first-parent <branch_name>
It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).
The key option is --first-parent
: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)
It prevents the commit forks from being displayed.
You can run the following and filter the size only. If your file was called somefilename
you can do the following
while :; do ls -lh | awk '/some*/{print $5}'; sleep 5; done
One of the many ideas.
If you have PHP installed as a command line tool (try issuing php
to the terminal and see if it works), your shebang (#!
) line needs to look like this:
#!/usr/bin/php
Put that at the top of your script, make it executable (chmod +x myscript.php
), and make a Cron job to execute that script (same way you'd execute a bash script).
You can also use php myscript.php
.
follow he steps. in pgadmin
host-DataBase-Schemas- public (click right) CREATE script- open file -(choose xxx.sql) , then click over the option execute query write result to file -export data file ok- then click in save.its all. it work to me.
note: error in version command script enter image description herede sql over pgadmin can be search, example: http://www.forosdelweb.com/f21/campo-tipo-datetime-postgresql-245389/
If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.
if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
WaitForAjax();
Thread.Sleep(3000);
}
else
{
Console.WriteLine("Your comment here);
}
This also happened to me when a PercentageRelativeLayout https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html was used and the build was targeting Android 0 = 26. PercentageRelativeLayout layout is obsolete starting from Android O and obviously sometime was changed in the resource generation. Replacing the layout with a ConstraintLayout or just a RelativeLayout solved it.
This is happening because there is no package cache in the image, you need to run:
apt-get -qq update
before installing packages, and if your command is in a Dockerfile, you'll then need:
apt-get -qq -y install curl
After that install ZSH and GIT Core:
apt-get install zsh
apt-get install git-core
Getting zsh
to work in ubuntu is weird since sh
does not understand the source command. So, you do this to install zsh
:
wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh
and then you change your shell to zsh:
chsh -s `which zsh`
and then restart:
sudo shutdown -r 0
This problem is explained in depth in this issue.
The following resolved the issue:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";
System.out.println(engine.eval(str));
Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).
If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
Here's a neat solution:
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if
/ else
in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if
/ else
version. For a cleaner / more readable solution, see @paxdiablo's answer.
Probably the best way to do this - assuming that you can't use the NOPASSWD solution provided by scottod is to use Mircea Vutcovici's solution in combination with Ansible vault.
For example, you might have a playbook something like this:
- hosts: all
vars_files:
- secret
tasks:
- name: Do something as sudo
service: name=nginx state=restarted
sudo: yes
Here we are including a file called secret
which will contain our sudo password.
We will use ansible-vault to create an encrypted version of this file:
ansible-vault create secret
This will ask you for a password, then open your default editor to edit the file. You can put your ansible_sudo_pass
in here.
e.g.: secret
:
ansible_sudo_pass: mysudopassword
Save and exit, now you have an encrypted secret
file which Ansible is able to decrypt when you run your playbook. Note: you can edit the file with ansible-vault edit secret
(and enter the password that you used when creating the file)
The final piece of the puzzle is to provide Ansible with a --vault-password-file
which it will use to decrypt your secret
file.
Create a file called vault.txt
and in that put the password that you used when creating your secret
file. The password should be a string stored as a single line in the file.
From the Ansible Docs:
.. ensure permissions on the file are such that no one else can access your key and do not add your key to source control
Finally: you can now run your playbook with something like
ansible-playbook playbook.yml -u someuser -i hosts --sudo --vault-password-file=vault.txt
The above is assuming the following directory layout:
.
|_ playbook.yml
|_ secret
|_ hosts
|_ vault.txt
You can read more about Ansible Vault here: https://docs.ansible.com/playbooks_vault.html
As you set application/x-www-form-urlencoded
as content type so data sent must be like this format.
String urlParameters = "param1=data1¶m2=data2¶m3=data3";
Sending part now is quite straightforward.
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}
Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded
.
private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
The solution comes from the display property.
Basically you need to make the two divs act like table cells. So instead of using float:left
, you'll have to use display:table-cell
on both divs, and for the dynamic width div you need to set width:auto;
also. The both divs should be placed into a 100% width container with the display:table
property.
Here is the css:
.container {display:table;width:100%}
#search {
width: 160px;
height: 25px;
display:table-cell;
background-color: #FFF;
}
#navigation {
width: auto;
display:table-cell;
/*background-color: url('../images/transparent.png') ;*/
background-color: #A53030;
}
*html #navigation {float:left;}
And the HTML:
<div class="container">
<div id="search"></div>
<div id="navigation"></div>
</div>
IMPORTANT:For Internet Explorer you need to specify the float property on the dynamic width div, otherwise the space will not be filled.
I hope that this will solve your problem. If you want, you can read the full article I wrote about this on my blog.
Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.
Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.
There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.
Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.
You can use java.sql.Date.valueOf()
method as:
Date date = java.sql.Date.valueOf(localDate);
No need to add time and time zone info here because they are taken implicitly.
See LocalDate to java.util.Date and vice versa simpliest conversion?
If you need to support other formats as well or just need good performance, you can use this WebAssembly library
it's promised based, it uses WebWorkers for threading and API is actually simple ES module
For Windows 7:
I got through this error "Module error Crypo.Cipher import AES"
To install Pycrypto in Windows,
Try this in Command Prompt,
Set path=C:\Python27\Scripts (i.e path where easy_install is located)
Then execute the following,
easy_install pycrypto
For Ubuntu:
Try this,
Download Pycrypto from "https://pypi.python.org/pypi/pycrypto"
Then change your current path to downloaded path using your terminal:
Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#
Then execute the following using the terminal:
python setup.py install
It's worked for me. Hope works for all..
I coded this simple decorator class to cache function responses. I find it VERY useful for my projects:
from datetime import datetime, timedelta
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=0))
def __call__(self, func):
def inner(*args, **kwargs):
max_age = kwargs.get('max_age', self.default_max_age)
if not max_age or func not in self.cached_function_responses or (datetime.now() - self.cached_function_responses[func]['fetch_time'] > max_age):
if 'max_age' in kwargs: del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func]['data']
return inner
The usage is straightforward:
import time
@cached
def myfunc(a):
print "in func"
return (a, datetime.now())
@cached(default_max_age = timedelta(seconds=6))
def cacheable_test(a):
print "in cacheable test: "
return (a, datetime.now())
print cacheable_test(1,max_age=timedelta(seconds=5))
print cacheable_test(2,max_age=timedelta(seconds=5))
time.sleep(7)
print cacheable_test(3,max_age=timedelta(seconds=5))
You can configure logging in your settings.py
file.
One example:
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.
SELECT @@IDENTITY AS 'Identity';
or
SELECT last_insert_id();
Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.
You don't need to harcode android:debuggable="false"
in your application tag. Infact for me studio complaints -
Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)
It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.
The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.
Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.
Now you should see a prompt to select release build or debug build
.
For production always select release build!
And you are done. Signed APK exported.
PS : Don't forget to increment your versionCode
in manifest file before uploading to playstore :)
I like to look at generating passwords, just like generating software keys. You should choose from an array of characters that follow a good practice. Take what @Radu094 answered with and modify it to follow good practice. Don't put every single letter in the character array. Some letters are harder to say or understand over the phone.
You should also consider using a checksum on the password that was generated to make sure that it was generated by you. A good way of accomplishing this is to use the LUHN algorithm.
1. another odd testing function
Ok, the assignment was handed in 8+ years ago, but here is another solution based on bit shifting operations:
def isodd(i):
return(bool(i>>0&1))
testing gives:
>>> isodd(2)
False
>>> isodd(3)
True
>>> isodd(4)
False
2. Nearest Odd number alternative approach
However, instead of a code that says "give me this precise input (an integer odd number) or otherwise I won't do anything" I also like robust codes that say, "give me a number, any number, and I'll give you the nearest pyramid to that number".
In that case this function is helpful, and gives you the nearest odd (e.g. any number f such that 6<=f<8 is set to 7 and so on.)
def nearodd(f):
return int(f/2)*2+1
Example output:
nearodd(4.9)
5
nearodd(7.2)
7
nearodd(8)
9
try using time with the elapsed seconds option:
/usr/bin/time -f%e sleep 1
under bash.
or \time -f%e sleep 1
in interactive bash.
see the time man page:
Users of the bash shell need to use an explicit path in order to run the external time command and not the shell builtin variant. On system where time is installed in /usr/bin, the first example would become /usr/bin/time wc /etc/hosts
and
FORMATTING THE OUTPUT
...
% A literal '%'.
e Elapsed real (wall clock) time used by the process, in
seconds.
For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.
For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).
Rather, you want to set the attribute in a before_validation on: create, like so:
before_validation :set_status_because_rails_cannot, on: :create
def set_status_because_rails_cannot
self.status ||= 'P'
end
I usually use this method
public static SelectList SetSelectedValue(SelectList list, string value)
{
if (value != null)
{
var selected = list.Where(x => x.Value == value).First();
selected.Selected = true;
return list;
}
return list;
}
List of Integer
.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
It's also possible to use jQuery's .load()
$('#submitform').click(function() {
$('#showresults').load('getinfo.asp #showresults', {
txtsearch: $('#appendedInputButton').val()
}, function() {
// alert('Load was performed.')
// $('#showresults').slideDown('slow')
});
});
unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):
hexdump -ve '1/1 "%.2x"'
1/1
means "each format is applied once and takes one byte", and "%.2x"
is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.
Putting spring.jpa.properties.hibernate.show_sql=true
in application.properties didn't help always.
You can try to add properties.put("hibernate.show_sql", "true");
to the properties of the database configuration.
public class DbConfig {
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
Map<String, Object> properties = new HashMap();
properties.put("hibernate.hbm2ddl.auto", "validate");
properties.put("hibernate.show_sql", "true");
return builder
.dataSource(dataSource)
.packages("com.test.dbsource.domain")
.persistenceUnit("dbsource").properties(properties)
.build();
}
The code of Ellbar works! You need only add using.
1 - using Microsoft.AspNet.Identity;
And... the code of Ellbar:
2 - string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
With this code (in currentUser
), you work the general data of the connected user, if you want extra data... see this link
I`m using the official jenkins docker image (https://hub.docker.com/r/jenkins/jenkins) but I think this solution is applicable to most use cases where we want to run Docker inside a Docker container.
The recommended way for using Docker inside a Docker container, is to use the Docker deamon of the host system. Good article regarding that: https://itnext.io/docker-in-docker-521958d34efd.
The secret to handle the permission issue, which this question is about, is to add permissions for the user of the container inside the container, not the host system. Only root user has permissions to do that by default, so
docker exec -it -u root <container-name> bash
usermod -a -G docker <username>
will do it. Remember to restart the container.
I guess the simpliest way to achive this is to create a customised Dockerfile:
# Official jenkins image
FROM jenkins/jenkins:lts
# Swith to root to be able to install Docker and modify permissions
USER root
RUN apt-get update
# Install docker
RUN curl -sSL https://get.docker.com/ | sh
# Add jenkins user to docker group
RUN usermod -a -G docker jenkins
# Switch back to default user
USER jenkins
# Bild the image:
# sudo docker build -t yourusername/imagename .
# Run the image and mount with the followin bind mount option:
# sudo docker run --name imagename -d -p8080:8080 -v /var/run/docker.sock:/var/run/docker.sock yourusername/imagename
I just added the Query key (Refit lib) in the property for the request.
[Query(CollectionFormat.Multi)]
public class ExampleRequest
{
[FromQuery(Name = "name")]
public string Name { get; set; }
[AliasAs("category")]
[Query(CollectionFormat.Multi)]
public List<string> Categories { get; set; }
}
In order to keep floating text in the same location over an image when changing browser zoom, I used this CSS:
position: absolute;
margin-top: -18%
I think the % instead of fixed pixels is what does it. Cheers!
You can use in the below format, Raw default value starting from 0, so
You can assign your own specific start value.
typedef enum : NSUInteger {
kCircle, // for your value; kCircle = 5, ...
kRectangle,
kOblateSpheroid
} ShapeType;
ShapeType circleShape = kCircle;
NSLog(@"%lu", (unsigned long) circleShape); // prints: 0
tried all above, didn't work. below solution works for me:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
</configuration>
try this below code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.blah"
>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000044"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:text="@string/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"/>
<EditText
android:id="@+id/editTitle"
android:text=""
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/description"
android:text="@string/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"/>
<EditText
android:id="@+id/editDescription"
android:text=""
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/location"
android:text="@string/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"/>
<EditText
android:id="@+id/editLocation"
android:text=""
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/startTime"
android:text="@string/startTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"/>
<DatePicker
android:id="@+id/DatePicker01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TimePicker
android:id="@+id/TimePicker01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/endTime"
android:text="@string/endTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"/>
<DatePicker
android:id="@+id/DatePicker02"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TimePicker
android:id="@+id/TimePicker02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/buttonCreate"
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout></ScrollView></RelativeLayout>
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
// your code...
}];
delete.image = [UIImage systemImageNamed:@"trash"];
UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:[[NSArray alloc] initWithObjects:delete, nil]];
return actions;
}
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
(1) No (unfortunately). Edit: The other answers are right, per-user configuration is usually stored in dot-files or dot-directories in the users home directory. Anything above user level often is a lot of guesswork.
(2) System-wide ini file -> user ini file -> environment -> command line options (going from lowest to highest precedence)
here, http://pieceofpy.com/2009/03/05/concatenating-pdf-with-python/, gives an solution.
similarly:
from pyPdf import PdfFileWriter, PdfFileReader
def append_pdf(input,output):
[output.addPage(input.getPage(page_num)) for page_num in range(input.numPages)]
output = PdfFileWriter()
append_pdf(PdfFileReader(file("C:\\sample.pdf","rb")),output)
append_pdf(PdfFileReader(file("c:\\sample1.pdf","rb")),output)
append_pdf(PdfFileReader(file("c:\\sample2.pdf","rb")),output)
append_pdf(PdfFileReader(file("c:\\sample3.pdf","rb")),output)
output.write(file("c:\\combined.pdf","wb"))
on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o
it still happens in Android Studio 1.5.1. on Ubuntu and you can solve it simply changing a setting from Gradle:
1) on app/build.gradle dependencies change from:
compile 'com.android.support:design:23.2.0'
to:
compile 'com.android.support:design:23.1.0'
2) rebuild project
3) refresh view
Best regards,
/Angel
Spring provides a very clean division between controllers, JavaBean models, and views.
To print the current state of the object you might:
>>> obj # in an interpreter
or
print repr(obj) # in a script
or
print obj
For your classes define __str__
or __repr__
methods. From the Python documentation:
__repr__(self)
Called by therepr()
built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines repr() but not__str__()
, then__repr__()
is also used when an "informal" string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
__str__(self)
Called by thestr()
built-in function and by the print statement to compute the "informal" string representation of an object. This differs from__repr__()
in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class']
.
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Easy solution if you don't want to code manually using Google Sheets Power Tools:
you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further
Use a table variable if for a very small quantity of data (thousands of bytes)
Use a temporary table for a lot of data
Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.
In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.
But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.
This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.
My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.
If you want an inbuilt function to dump your data into some github markdown, you now have one. Take a look at to_markdown
:
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
print(df.to_markdown())
| | A | B |
|:---|----:|----:|
| a | 1 | 1 |
| a | 2 | 2 |
| b | 3 | 3 |
Here's what that looks like on github:
Note that you will still need to have the tabulate
package installed.
We can't because it's expected/required by our customers.
I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:
DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");
using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
This can not be done easily. There's no way to make an NVARCHAR
parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.
Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:
CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
IF NOT <@PortfolioID contains Comma>
BEGIN
INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
SET @PortfolioID = ''
END ELSE
BEGIN
INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
SET @PortfolioID = <Everything after the next comma>
END
END
Then, change your condition to
WHERE PortfolioId IN (SELECT ID FROM #TempTable)
EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:
You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:
The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.
The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.
The query must use an IN clause to specify the parameter.
find . -name "*.pyc"|xargs rm -rf
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
keycloak version: 4.6.0
You haven't shown your Car
type, but assuming you'd want the price of the first car, you could use:
public static void processCars(ArrayList<Car> cars) {
Car car = cars.get(0);
System.out.println(car.getPrice());
}
Note that I've changed the name of the list from car
to cars
- this is a list of cars, not a single car. (I've changed the method name in a similar way.)
If you only want the method to process a single car, you should change the parameter to be of type Car
:
public static void processCar(Car car)
and then call it like this:
// In the main method
processCar(cars.get(0));
If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car>
- it's unlikely that you'll really require that it's an ArrayList<Car>
.
I like these commands as they use svn status
to find the new or missing files, which respects files that are ignored.
svn add $( svn status | sed -e '/^?/!d' -e 's/^?//' )
svn rm $( svn status | sed -e '/^!/!d' -e 's/^!//' )
I ended up creating my own plugin. Here it is in case this helps anyone:
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
Here's some sample code of how to use it:
<script type="text/javascript"><!--
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 1000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
//--></script>
<span class="timer"></span>
View the demo on JSFiddle: http://jsfiddle.net/YWn9t/
Where a
is the slice, and i
is the index of the element you want to delete:
a = append(a[:i], a[i+1:]...)
...
is syntax for variadic arguments in Go.
Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println
can take as many arguments as you want).
Now, when calling a function, ...
does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.
So what this line does:
a = append(a[:0], a[1:]...)
is essentially:
a = append(a[:0], a[1], a[2])
Now, you may be wondering, why not just do
a = append(a[1:]...)
Well, the function definition of append
is
func append(slice []Type, elems ...Type) []Type
So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.
If you know the element type then: (eg: replace 'element' with 'div')
$("element[id$='txtTitle']")
If you don't know the element type:
$("[id$='txtTitle']")
// the old way, needs exact ID: document.getElementById("hi").value = "kk";_x000D_
$(function() {_x000D_
$("[id$='txtTitle']").val("zz");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="ctl_blabla_txtTitle" type="text" />
_x000D_
How about .toDateString()
?
Alternatively, use .getDate()
, .getMonth()
, and .getYear()
?
In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?
Check out all the fun Date methods here: MDN Docs
Edit: If you want to keep it as a date object, just do this:
var newDate = new Date(oldDate.toDateString());
Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.
Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure
Here's a simplified view of the file structure:
chat-1-bob.txt
201101011029, hi
201101011030, fine thanks.
chat-1-jen.txt
201101011030, how are you?
201101011035, have you spoken to bill recently?
chat-2-bob.txt
201101021200, hi
201101021222, about 12:22
chat-2-bill.txt
201101021201, Hey Bob,
201101021203, what time do you call this?
You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.
I think you will find it hard to get a more simple scaleable solution.
You can use LOAD_FILE
to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.
In general, smoke and sanity testing seems very similar to many tester who have just started, because in both we talk about build, we talk about functionality and we talk about the rejection of builds, if build's health is not good for the feasible testing.
After going through several projects, from start ups to product base company, I figured out the basic difference between smoke and sanity testing.
I am writing difference between smoke testing and sanity testing here to help you in answering at least one question that normally all testers get asked in interview.
Smoke testing is done to test the health of builds.
It is also known as the shallow and wide testing, in that we normally include those test cases which can cover all the functionality of the product.
We can say that it's the first step of testing and, after this, we normally do other kind of functional and system testing, including regression testing.
It's normally done by a developer with the help of certain scripts or certain tools, but in some cases it can be performed by a tester too.
It's valid for initial stage of a build confirmation. For example, suppose we have started the development of a certain product, and we are producing a build for the first time, then smoke testing becomes a necessity for the product.
It is sub-regression
Sanity is done for those builds which have gone through many regression tests and a minor change in code has happened. In this case, we normally do the intensive testing of functionalities where this change has occurred or may have influenced.
It's performed by a tester
It's done for mature builds, like those that are just going to hit production, and have gone through multiple regression processes.
It can be removed from the testing process, if regression is already being performed.
If any build doesn't pass the sanity tests, then it is thrown to developer back for the correction of the build.
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
In case of Oracle since 12c you have DEFAULT ON NULL
which implies a NOT NULL
constraint.
ALTER TABLE tbl ADD (col VARCHAR(20) DEFAULT ON NULL 'MyDefault');
ON NULL
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified. If you specify an inline constraint that conflicts with NOT NULL and NOT DEFERRABLE, then an error is raised.
As Andy said the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:
void HTMLParser::processCloseTag(Token* t)
{
// Support for really broken html.
// we never close the body tag, since some stupid web pages close it before
// the actual end of the doc.
// let's rely on the end() call to close things.
if (t->tagName == htmlTag || t->tagName == bodyTag
|| t->tagName == commentAtom)
return;
...
from urllib import request
def get(url):
with request.urlopen(url) as r:
return r.read()
def download(url, file=None):
if not file:
file = url.split('/')[-1]
with open(file, 'wb') as f:
f.write(get(url))
Instead of using list.index(x)
which returns the index of x if it is found in list or returns a #ValueError
message if x is not found, you could use list.count(x)
which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count()
is that it doesn't break your code or require you to throw an exception for when x is not found
The problem is that your img
s will always bump down to the next line because of the containing div
.
In order to get around this, you need to place the img
s in their own div
with a width
wide enough to hold all of them. Then you can use your styles as is.
So, when I set the img
s to 120px
each and place them inside a
div#insideDiv{
width:800px;
}
it all works.
Adjust width as necessary.
Declare a SecondActivity variable in FirstActivity
Like this
public class FirstActivity extends Activity {
SecondActivity secactivity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
public void method() {
// some code
secactivity.call_method();// 'Method' is Name of the any one method in SecondActivity
}
}
Using this format you can call any method from one activity to another.
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
In the project navigator, select your project.
Select your target.
Select the "Build Phases" tab.
expander. Click the + button.
Select your framework.
(optional) Drag and drop the added framework to the "Frameworks" group.
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
You want the CASE
statement:
SELECT
CASE
WHEN @SelectField1 = 1 THEN Field1
WHEN @SelectField2 = 1 THEN Field2
ELSE NULL
END AS NewField
FROM Table
EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.
I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.
It seems Helper
, Manager
, and Util
are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator
.
You could get particularly purple prosey with the names and go for things like Minder
, Overseer
, Supervisor
, Administrator
, and Master
, but as I said I prefer keeping it like the framework names you're used to.
Some other common suffixes (if that is the correct term) you also find in the .NET framework are:
Builder
Writer
Reader
Handler
Container
I think this should help:
Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm
var jsonfile = require("./path/to/jsonfile.json");
node = jsonfile.adjacencies.nodeTo;
node2 = jsonfile.adjacencies.nodeFrom;
node3 = jsonfile.adjacencies.data.$color;
//other things.
Today in Visual Studio 2017 I had the same problem.
The cause in my case turned out to be a bad environment setting in NETFXSDKDir (NETFXSDKDir=C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1
). It needs to be instead NETFXSDKDir=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86
. Specifically, as set in this batch file (my directory actually has 4 different files) for the Command Prompt for VS2017:
%comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvars32.bat"
as I am reluctant to change one of the "as installed" batch files… even more as that batch file calls another yet another:
@call "%~dp0vcvarsall.bat" x86 %*
...instead for my specific C++ command-line app, I simply added the explicit path text: ;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86
for a total string in "Library Directories" like this: $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86
. (Right click on project, Properties → Configuration Properties → VC++ Directories → Library Directories.) That resolved my "fatal error LNK1104: cannot open file 'kernel32.lib'" error. I found that hint in this GitHub issue.
Note this is reproducible in Visual Studio 2017 Enterprise 2017 Version 15.1 (26403.0) even after successful "repair" install… when creating a new Visual C++ Win32 Console Application and attempting to compile.
In fact, unless a blank application is created, the default template also includes reference to <SDKDDKVer.h>
and with that I get this additional error: Error (active) E1696 cannot open source file "SDKDDKVer.h"
. So I created an empty C++ project.
If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:
I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.
Due to the generated export, there have been a bunch of "GO" statements in the sql file.
What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!
Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.
This page may help: http://www.gnu.org/software/make/
Set objFSO=CreateObject("Scripting.FileSystemObject")
' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close
'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine= objFile.ReadLine
Wscript.Echo strLine
Loop
objFile.Close
'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)
this will open the file with the default windows program (notepad if you haven't changed it);
Process.Start(@"c:\myfile.txt")
Easiest way:
byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
buffer = new byte[stream.Length - 1];
stream.Read(buffer, 0, buffer.Length);
}
using (Stream stream = new IO.FileStream("newFile.pdf"))
{
stream.Write(buffer, 0, buffer.Length);
}
Or something along these lines...
Remember that when you write:
MyArray = Range("A1:A5000")
you are really writing
MyArray = Range("A1:A5000").Value
You can also use names:
MyArray = Names("MyWSTable").RefersToRange.Value
But Value is not the only property of Range. I have used:
MyArray = Range("A1:A5000").NumberFormat
I doubt
MyArray = Range("A1:A5000").Font
would work but I would expect
MyArray = Range("A1:A5000").Font.Bold
to work.
I do not know what formats you want to copy so you will have to try.
However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.
Post Edit information
Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.
Of the following statements, the second would fail with a type mismatch:
ValueArray = .Range("A1:T5000").Value
ColourArray = .Range("A1:T5000").Font.Color
ValueArray must be of type variant. I tried both variant and long for ColourArray without success.
I filled ColourArray with values and tried the following statement:
.Range("A1:T5000").Font.Color = ColourArray
The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.
There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.
I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.
With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.
With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.
With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.
Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.
** Code for Version 1**
I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.
Sub SelectionCopyAndPaste()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
NumSelect = NumSelect + 7
Loop
Debug.Print Timer - StartTime
' Average 12.43 secs
Application.Calculation = xlCalculationAutomatic
End Sub
** Code for Versions 2 and 3**
The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.
Type ValueDtl
Value As String
Colour As Long
End Type
Sub SelectionViaArray()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim InxVLCrnt As Integer
Dim InxVLCrntMax As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Dim ValueList() As ValueDtl
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' I have sized the array to more than I expect to require because ReDim
' Preserve is expensive. However, I will resize if I fill the array.
' For my experiment I know exactly how many elements I need but that
' might not be true for you.
ReDim ValueList(1 To 25000)
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
InxVLCrntMax = 0 ' Last used element in ValueList.
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
With Sheets("Time1")
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
InxVLCrntMax = InxVLCrntMax + 1
If InxVLCrntMax > UBound(ValueList) Then
' Resize array if it has been filled
ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
End If
With .Cells(RowSrcCrnt, ColSrcCrnt)
ValueList(InxVLCrntMax).Value = .Value ' Version 2
ValueList(InxVLCrntMax).Value = .Formula ' Version 3
ValueList(InxVLCrntMax).Colour = .Font.Color
End With
NumSelect = NumSelect + 7
Loop
End With
With Sheets("Time2")
For InxVLCrnt = 1 To InxVLCrntMax
With .Cells(RowDestCrnt, ColDestCrnt)
.Value = ValueList(InxVLCrnt).Value ' Version 2
.Formula = ValueList(InxVLCrnt).Value ' Version 3
.Font.Color = ValueList(InxVLCrnt).Colour
End With
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
Next
End With
Debug.Print Timer - StartTime
' Version 2 average 1.47 secs
' Version 3 average 1.83 secs
Application.Calculation = xlCalculationAutomatic
End Sub
Can you give this a try,
return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));
While, you can set multiple variables something like this,
$instructors="";
$instituitions="";
$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);
return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
Use genfromtxt
instead. It's a much more general method than loadtxt
:
import numpy as np
print np.genfromtxt('col.txt',dtype='str')
Using the file col.txt
:
foo bar
cat dog
man wine
This gives:
[['foo' 'bar']
['cat' 'dog']
['man' 'wine']]
If you expect that each row has the same number of columns, read the first row and set the attribute filling_values
to fix any missing rows.
I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S
:
# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80 is a NameVirtualHost
default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
[...]
11.22.33.44:443 is a NameVirtualHost
default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80 hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001 hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000 hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443 hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001 hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000 hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK
Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).
Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default
on line 33 and /etc/apache2/sites-enabled/default-ssl
on line 163. Likewise *:30000
is listed in 2 places. The solution (in my case) was simply to delete one of the entries.
Use below code to convert String Date to Epoc Timestamp. Note : - Your input Date format should match with SimpleDateFormat.
String inputDateInString= "8/15/2017 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyy hh:mm:ss");
Date parsedDate = dateFormat.parse("inputDateInString");
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("Timestamp "+ timestamp.getTime());
If using mvn
, check that you have the correct scope (if you have that defined) in your pom.xml
. I once had it incorrectly set to test but needed it for runtime.
pip install pywin32
didn't work for me but pypiwin32
did.
I know this thread is old.... but I faced the same problem... If you are willing to use thread.join()
import threading
class test:
def __init__(self):
self.msg=""
def hello(self,bar):
print('hello {}'.format(bar))
self.msg="foo"
def main(self):
thread = threading.Thread(target=self.hello, args=('world!',))
thread.start()
thread.join()
print(self.msg)
g=test()
g.main()
"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess
file are world-readable.
From the documentation:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
That means it is timezone naive, so you can't use it with datetime.astimezone
you can give it a timezone like this
import pytz # 3rd party: $ pip install pytz
u = datetime.utcnow()
u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset
now you can change timezones
print(u.astimezone(pytz.timezone("America/New_York")))
To get the current time in a given timezone, you could pass tzinfo to datetime.now()
directly:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
print(datetime.now(pytz.timezone("America/New_York")))
It works for any timezone including those that observe daylight saving time (DST) i.e., it works for timezones that may have different utc offsets at different times (non-fixed utc offset). Don't use tz.localize(datetime.now())
-- it may fail during end-of-DST transition when the local time is ambiguous.
the easiest way would be
which means you could just do:
new File(filename).text
I don't have enough reputation to comment answer of @user1615903, so add this as answer: "git remote remove" does not exist, should use "rm" instead of "remove". So the correct way is:
git remote rm origin
document.getElementById('foo').disabled = true;
or
document.getElementById('foo').readOnly = true;
Note that readOnly
should be in camelCase to work correctly in Firefox (magic).
Demo: https://jsfiddle.net/L96svw3c/ -- somewhat explains the difference between disabled
and readOnly
.
From the UIView reference's section about the beginAnimations:context:
method:
Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.
Eg of Block-based Animation based on Tom's Comment
[UIView transitionWithView:mysuperview
duration:0.75
options:UIViewAnimationTransitionFlipFromRight
animations:^{
[myview removeFromSuperview];
}
completion:nil];
I've never had a good memory for exact wording, but in my database class I think the professor always said something like:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].
If you don't want the weekends to appear at all, simply:
CSS
th.ui-datepicker-week-end,
td.ui-datepicker-week-end {
display: none;
}
Just reposting @bucababy's answer as a "bookmarklet", as it's sometimes easier than using those lookup pages:
alert(prompt('Enter characters to htmlEncode', '').replace(/[\u00A0-\u2666]/g, function(c) {
return '&#'+c.charCodeAt(0)+';';
}));
fwiw, an example using "RestEasy" implementation of JAX-RS 2.x to build a special "trust all" client...
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import javax.ejb.Stateless;
import javax.net.ssl.SSLContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.TrustStrategy;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
@Stateless
@Path("/postservice")
public class PostService {
private static final Logger LOG = LogManager.getLogger("PostService");
public PostService() {
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {
//...object passed to the POST method...
PostDTO requestObject = new PostDTO();
requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));
//...build special "trust all" client to call POST method...
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));
//...object returned from the POST method...
PostRespDTO responseObject = response.readEntity(PostRespDTO.class);
response.close();
return responseObject;
}
//...get special "trust all" client...
private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
HttpClientBuilder builder = HttpClientBuilder.create();
NoopHostnameVerifier noop = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
}
private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
};
}
related Maven dependencies
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.10.Final</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
There are a few ways to use log4net. I found it is useful while I was searching for a solution. The solution is described here: https://www.hemelix.com/log4net/
The reason this occurs is because the file is stored in the "cache" of the browser – so there is no need for the browser to request the sheet again. This occurs for most files that your HTML links to – whether they're CDNs or on your server, for example, a stylesheet. A hard refresh will reload the page and send new GET requests to the server (and to external b if needed).
You can also empty the caches in most browsers with the following keyboard shortcuts.
Safari: Cmd+Alt+e
Chrome and Edge: Shift+Cmd+Delete (Mac) and Ctrl+Shift+Del (Windows)
Here's the code from Marc Gravell's answer, along with an example of using it.
using System;
using System.Collections.Generic;
using System.Linq;
public static class Utils
{
public static bool IsAny<T>(this IEnumerable<T> data)
{
return data != null && data.Any();
}
}
class Program
{
static void Main(string[] args)
{
IEnumerable<string> items;
//items = null;
//items = new String[0];
items = new String[] { "foo", "bar", "baz" };
/*** Example Starts Here ***/
if (items.IsAny())
{
foreach (var item in items)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("No items.");
}
}
}
As he says, not all sequences are repeatable, so that code may sometimes cause problems, because IsAny()
starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check for null
and empty. Often, you can just check for null and then use foreach
.
To avoid starting the sequence twice and take advantage of foreach
, I just wrote some code like this:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
IEnumerable<string> items;
//items = null;
//items = new String[0];
items = new String[] { "foo", "bar", "baz" };
/*** Example Starts Here ***/
bool isEmpty = true;
if (items != null)
{
foreach (var item in items)
{
isEmpty = false;
Console.WriteLine(item);
}
}
if (isEmpty)
{
Console.WriteLine("No items.");
}
}
}
I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that IsAny(items)
will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)
I think you cant remove column names, only reset them by range
with shape
:
print df.shape[1]
2
print range(df.shape[1])
[0, 1]
df.columns = range(df.shape[1])
print df
0 1
0 23 12
1 21 44
2 98 21
This is same as using to_csv
and read_csv
:
print df.to_csv(header=None,index=False)
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
0 1
0 23 12
1 21 44
2 98 21
Next solution with skiprows
:
print df.to_csv(index=False)
A,B
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
0 1
0 23 12
1 21 44
2 98 21
If you are using Swift, this is how you do it
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = self.view.center
activityView.startAnimating()
self.view.addSubview(activityView)
I haven't figure out the reason but reinstalling the .pfx
certificate(both in current user and local machine) works for me.
I am trying to do a robot to my little son and just play a Youtube video and than show a robot dancing.
For some reason, commands like CONTROL + T explained above was not working for me and maybe it is not the correct answer but I solved my problem using custom Javascript script like this:
using (var driver = new ChromeDriver())
{
var link1 = "https://www.youtube.com/watch?v=0GIgk4yuHOQ";
//open a music
driver.Navigate().GoToUrl(link1);
var link2 = "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/fbe53d6d-c13f-4eec-9bcf-62f19cfab15a/d4m0h4v-9442b1f2-6a49-4818-8f51-5ebe216f043c.gif?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwic3ViIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsImF1ZCI6WyJ1cm46c2VydmljZTpmaWxlLmRvd25sb2FkIl0sIm9iaiI6W1t7InBhdGgiOiIvZi9mYmU1M2Q2ZC1jMTNmLTRlZWMtOWJjZi02MmYxOWNmYWIxNWEvZDRtMGg0di05NDQyYjFmMi02YTQ5LTQ4MTgtOGY1MS01ZWJlMjE2ZjA0M2MuZ2lmIn1dXX0.BTTlingNpBqH5O9dNVienFsArNqkfUc7KXnIgHumrBQ";
//Dance robot, dance
driver.ExecuteScript($"window.open('{link2}', '_blank');");
Thread.Sleep(20000);
}
I think the shortest way is:
var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();
Read Google-gson
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Add the following line to your MODULE LEVEL build.gradle
configuration:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5' // Old 2.8.2
}
The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.
It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.
As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.
What is the use of e.printStackTrace() method in Java?
Well, the purpose of using this method e.printStackTrace();
is to see what exactly wrong is.
For example, we want to handle an exception. Let's have a look at the following Example.
public class Main{
public static void main(String[] args) {
int a = 12;
int b = 2;
try {
int result = a / (b - 2);
System.out.println(result);
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
I've used method e.printStackTrace();
in order to show exactly what is wrong.
In the output, we can see the following result.
Error: / by zero
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
One possible cause, it that you've enabled the "pause on exceptions" (the little stop-sign shaped icon with the pause (||) symbol with in in the lower left of the window). Try clicking that back to the off/grey state (not red nor blue states) and reload the page.
UPDATE: Adding a screenshot for reference:
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
The ID Should have the id of the corresponding div that has the overflow css property.
document.querySelector('#YOUR_OVERFLOWED_DIV').scrollTop = 0;
As mentioned by @jerry you can add services with the below command.
update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service> remove
To validate them check the above commands you can check /etc/rc*.d/ directory where service start with "k" means it will not execute during the boot and service start with "S" will start during the boot.
# for runlevel symlinks:
ls /etc/rc*.d/
In the below screenshot you can see apache2 starting in runlevel2(S02apache2) and stopping in runlevel1(K01apache2)
You can also check the service status with the below command where "+" means service is in running state "-" is in stopped.
service --status-all
OR
install sysv-rc-conf utility.
apt-get install sysv-rc-conf
example
sysv-rc-conf --level 2345 apach22 on
man sysv-rc-conf
http://sourceforge.net/projects/xampp/files/
The old version, but the desired function will be sufficient.
Uninstall version 5.6.11 and downgrade to version 5.6.8.
Use .ashx file type and use the same code
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')