for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Working solution with validate email,mobile number
public class ExcelProcessing
{
public List<ExcelUserData> ReadExcel()
{
string path = Config.folderPath + @"\MemberUploadFormat.xlsx";
using (var excelPack = new ExcelPackage())
{
//Load excel stream
using (var stream = File.OpenRead(path))
{
excelPack.Load(stream);
}
//Lets Deal with first worksheet.(You may iterate here if dealing with multiple sheets)
var ws = excelPack.Workbook.Worksheets[0];
List<ExcelUserData> userList = new List<ExcelUserData>();
int colCount = ws.Dimension.End.Column; //get Column Count
int rowCount = ws.Dimension.End.Row;
for (int row = 2; row <= rowCount; row++) // start from to 2 omit header
{
bool IsValid = true;
ExcelUserData _user = new ExcelUserData();
for (int col = 1; col <= colCount; col++)
{
if (col == 1)
{
_user.FirstName = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.FirstName))
{
_user.ErrorMessage += "Enter FirstName <br/>";
IsValid = false;
}
}
else if (col == 2)
{
_user.Email = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.Email))
{
_user.ErrorMessage += "Enter Email <br/>";
IsValid = false;
}
else if (!IsValidEmail(_user.Email))
{
_user.ErrorMessage += "Invalid Email Address <br/>";
IsValid = false;
}
}
else if (col ==3)
{
_user.MobileNo = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.MobileNo))
{
_user.ErrorMessage += "Enter Mobile No <br/>";
IsValid = false;
}
else if (_user.MobileNo.Length != 10)
{
_user.ErrorMessage += "Invalid Mobile No <br/>";
IsValid = false;
}
}
else if (col == 4)
{
_user.IsAdmin = ws.Cells[row, col].Value?.ToString().Trim();
if (string.IsNullOrEmpty(_user.IsAdmin))
{
_user.IsAdmin = "0";
}
}
_user.IsValid = IsValid;
}
userList.Add(_user);
}
return userList;
}
}
public static bool IsValidEmail(string email)
{
Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
return regex.IsMatch(email);
}
}
I prefer to use GNU datamash for such tasks because it's more succinct and legible than perl or awk. For example
datamash sum 1 < myfile
where 1 denotes the first column of data.
Take a look also to the do { ... }
command since gnuplot 4.6 as it is very powerful:
do for [t=0:50] {
outfile = sprintf('animation/bessel%03.0f.png',t)
set output outfile
splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}
For editing use
vi galfit.feedme //if user has file editing permissions
or
sudo vi galfit.feedme //if user doesn't have file editing permissions
For inserting
Press i //Do required editing
For exiting
Press Esc
:wq //for exiting and saving
:q! //for exiting without saving
The width and height are only for example:
parentDiv{
width: 100px;
height: 100px;
position:relative;
}
innerDiv{
width: 200px;
height: 200px;
position:absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
You can use this simple code:
<embed src="audio.mp3" AutoPlay loop hidden>
for the result seen here: https://hataken.000webhostapp.com/list-anime.html
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
JavaScript:
function checkvalue() {
var mystring = document.getElementById('myString').value;
if(!mystring.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
alert("correct input");
return true;
}
}
HTML:
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"aß?de??????µ???p??st?f???"
>>> print len(greek)
25
>>> print greek[:10]
aß?de?????
If you want to run the above code as a script, put this line at the top
# -*- coding: utf-8 -*-
If your editor doesn't save in utf-8, substitute the correct encoding
try this
<body>
<div class="linkCollection">
<a tabindex=1 href="www.demo1.com">link</a>
<a tabindex=2 href="www.demo2.com">link</a>
<a tabindex=3 href="www.demo3.com">link</a>
<a tabindex=4 href="www.demo4.com">link</a>
<a tabindex=5 href="www.demo5.com">link</a>
<a tabindex=6 href="www.demo6.com">link</a>
<a tabindex=7 href="www.demo7.com">link</a>
<a tabindex=8 href="www.demo8.com">link</a>
<a tabindex=9 href="www.demo9.com">link</a>
<a tabindex=10 href="www.demo10.com">link</a>
</div>
</body>
<script>
$(document).ready(function(){
$(".linkCollection a").focus(function(){
var href=$(this).attr('href');
console.log(href);
// href variable holds the active selected link.
});
});
</script>
don't forgot to add jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
A simple method by using for
loop :
import os
dir = ["e","x","e"]
p = os.listdir('E:') #path
for n in range(len(p)):
name = p[n]
myfile = [name[-3],name[-2],name[-1]] #for .txt
if myfile == dir :
print(name)
else:
print("nops")
Though this can be made more generalised .
itertools.groupby
is a tool for grouping items.
From the docs, we glean further what it might do:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
groupby
objects yield key-group pairs where the group is a generator.
Features
Comparisons
# Define a printer for comparing outputs
>>> def print_groupby(iterable, keyfunc=None):
... for k, g in it.groupby(iterable, keyfunc):
... print("key: '{}'--> group: {}".format(k, list(g)))
# Feature A: group consecutive occurrences
>>> print_groupby("BCAACACAADBBB")
key: 'B'--> group: ['B']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A', 'A']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A', 'A']
key: 'D'--> group: ['D']
key: 'B'--> group: ['B', 'B', 'B']
# Feature B: group all occurrences
>>> print_groupby(sorted("BCAACACAADBBB"))
key: 'A'--> group: ['A', 'A', 'A', 'A', 'A']
key: 'B'--> group: ['B', 'B', 'B', 'B']
key: 'C'--> group: ['C', 'C', 'C']
key: 'D'--> group: ['D']
# Feature C: group by a key function
>>> # islower = lambda s: s.islower() # equivalent
>>> def islower(s):
... """Return True if a string is lowercase, else False."""
... return s.islower()
>>> print_groupby(sorted("bCAaCacAADBbB"), keyfunc=islower)
key: 'False'--> group: ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']
key: 'True'--> group: ['a', 'a', 'b', 'b', 'c']
Uses
Note: Several of the latter examples derive from Víctor Terrón's PyCon (talk) (Spanish), "Kung Fu at Dawn with Itertools". See also the groupby
source code written in C.
* A function where all items are passed through and compared, influencing the result. Other objects with key functions include sorted()
, max()
and min()
.
Response
# OP: Yes, you can use `groupby`, e.g.
[do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)]
It worked well for me. Just one line code in cmd.
First, confirm that you have installed the gcc (for c) or g++ (for c++) compiler.
In cmd for gcc type:
gcc --version
in cmd for g++ type:
g++ --version
If it is installed then proceed.
Now, compile your .c or .cpp using cmd
for .c syntax:
gcc -o exe_filename yourfilename.c
Example:
gcc -o myfile myfile.c
Here exe_filename (myfile in example) is the name of your .exe file which you want to produce after compilation (Note: i have not put any extension here). And yourfilename.c (myfile.c in example) is the your source file which has the .c extension.
Now go to folder containing your .c file, here you will find a file with .exe extension. Just open it. Hurray..
For .cpp syntax:
g++ -o exe_filename yourfilename.cpp
After it the process is same as for .c .
Found the answer. In the file xampp\apache\conf\extra\httpd-ssl.conf
, under the comment SSL Virtual Host Context
pages on port 443 meaning https is looked up under different document root.
Simply change the document root to the same one and problem is fixed.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
Head First SQL is a great introduction.
Simply write the following code in onBackPressed:
@Override
public void onBackPressed() {
// super.onBackPressed();
//Creating an alert dialog to logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Do you want to Exit?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
No it doesn't. I would expect this in a future api release, but for now we are stuck with EditText. Another option is this library:
https://github.com/marvinlabs/android-floatinglabel-widgets
My app was an ASP.Net3.5 app (using version 2 of the framework). When ASP.Net3.5 apps got created Visual Studio automatically added scriptResourceHandler to the web.config. Later versions of .Net put this into the machine.config. If you run your ASP.Net 3.5 app using the version 4 app pool (depending on install order this is the default app pool), you will get this error.
When I moved to using the version 2.0 app pool. The error went away. I then had to deal with the error when serving WCF .svc :
HTTP Error 404.17 - Not Found The requested content appears to be script and will not be served by the static file handler
After some investigation, it seems that I needed to register the WCF handler. using the following steps:
The error is not refering to myfunction
but to start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function_x000D_
const myfunction = async function(x, y) {_x000D_
return [_x000D_
x,_x000D_
y,_x000D_
];_x000D_
}_x000D_
_x000D_
// Start function_x000D_
const start = async function(a, b) {_x000D_
const result = await myfunction('test', 'test');_x000D_
_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// Call start_x000D_
start();
_x000D_
I use the opportunity of this question to advise you about an known anti pattern using await
which is : return await
.
WRONG
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// useless async here_x000D_
async function start() {_x000D_
// useless await here_x000D_
return await myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
CORRECT
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// Also point that we don't use async keyword on the function because_x000D_
// we can simply returns the promise returned by myfunction_x000D_
function start() {_x000D_
return myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
Also, know that there is a special case where return await
is correct and important : (using try/catch)
An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )
git fetch upstream --tags
Give me
From https://github.com/keycloak/keycloak
90b29b0e31..0ba9055d28 stage -> upstream/stage
* [new tag] 11.0.0 -> 11.0.0
Then I can create a new branch from this tag and checkout on it
git checkout -b tags/<name> <newbranch>
git checkout tags/11.0.0 -b v11.0.0
SELECT * FROM SysColumns WHERE Name like 'a%'
Will get you a list of columns, you will want to filter more to restrict it to your target table
From there you can construct some ad-hoc sql
Haha, oh boy, I figured it out. Somehow, someway, I did not install the Database Engine when I installed SQL Server 2008. I have no idea how I missed that, but that's what happened.
You need to install Xcode from App Store.
Then start Xcode, go to Xcode->Preferences->Downloads
and install component named "Command Line Tools".
After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.
The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
Here is simple example using wait
.
Run some processes:
$ sleep 10 &
$ sleep 10 &
$ sleep 20 &
$ sleep 20 &
Then wait for them with wait
command:
$ wait < <(jobs -p)
Or just wait
(without arguments) for all.
This will wait for all jobs in the background are completed.
If the -n
option is supplied, waits for the next job to terminate and returns its exit status.
See: help wait
and help jobs
for syntax.
However the downside is that this will return on only the status of the last ID, so you need to check the status for each subprocess and store it in the variable.
Or make your calculation function to create some file on failure (empty or with fail log), then check of that file if exists, e.g.
$ sleep 20 && true || tee fail &
$ sleep 20 && false || tee fail &
$ wait < <(jobs -p)
$ test -f fail && echo Calculation failed.
Plus what @mlc-mlapis commented, you're mixing lettable operators and the prototype patching method. Use one or the other.
For your case it should be
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class SwPeopleService {
people$ = this.http.get('https://swapi.co/api/people/')
.map((res:any) => res.results);
constructor(private http: HttpClient) {}
}
https://stackblitz.com/edit/angular-http-observables-9nchvz?file=app%2Fsw-people.service.ts
Let's say you have a collection named $services
that you are passing to the view.
If you need a JS array with the names, you can iterate over this as follows:
<script>
const myServices = [];
@foreach ($services as $service)
myServices.push('{{ $service->name }}');
@endforeach
</script>
Note: If the string has special characters (like ó
or HTML code), you can use {!! $service->name !!}
.
If you need an array of objects (with all of the attributes), you can use:
<script>
const myServices = @json($services);
// ...
</script>
Note: This blade directive @json
is not available for old Laravel versions. You can achieve the same result using json_encode
as described in other answers.
Sometimes you don't need to pass a complete collection to the view, and just an array with 1 attribute. If that's your case, you better use $services = Service::pluck('name');
in your Controller.
I tried all the listed solutions above but nothing worked. This is what worked for me.
Just use Val()
:
currentLoad = Int(Val([f4]))
Now currentLoad
has a integer value, zero if [f4]
is not numeric.
I always do it like this:
$("#id").css("width", "50%");
You could also do
var x = $('#element').height(); // or any changing value
$('selector').css({'top' : x + 'px'});
OR
You can use directly
$('#element').css( "height" )
The difference between .css( "height" )
and .height()
is that the latter returns a unit-less pixel value (for example, 400
) while the former returns a value with units intact (for example, 400px
). The .height() method is recommended when an element's height needs to be used in a mathematical calculation. jquery doc
int is nothing but an interruption i.e the processor will put its current execution to hold.
0x80 is nothing but a system call or the kernel call. i.e the system function will be executed.
To be specific 0x80 represents rt_sigtimedwait/init_module/restart_sys it varies from architecture to architecture.
For more details refer https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md
@Namphibian's suggestion helped me a lot...
went a little further though and added columns and views to the script
just enter your schema's name below and it will do the rest
-- set your table name here
SET @MY_SCHEMA = "";
-- tables
SELECT DISTINCT
CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=@MY_SCHEMA
AND TABLE_TYPE="BASE TABLE"
UNION
-- table columns
SELECT DISTINCT
CONCAT("ALTER TABLE ", C.TABLE_NAME, " CHANGE ", C.COLUMN_NAME, " ", C.COLUMN_NAME, " ", C.COLUMN_TYPE, " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.COLUMNS as C
LEFT JOIN INFORMATION_SCHEMA.TABLES as T
ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLLATION_NAME is not null
AND C.TABLE_SCHEMA=@MY_SCHEMA
AND T.TABLE_TYPE="BASE TABLE"
UNION
-- views
SELECT DISTINCT
CONCAT("CREATE OR REPLACE VIEW ", V.TABLE_NAME, " AS ", V.VIEW_DEFINITION, ";") as queries
FROM INFORMATION_SCHEMA.VIEWS as V
LEFT JOIN INFORMATION_SCHEMA.TABLES as T
ON V.TABLE_NAME = T.TABLE_NAME
WHERE V.TABLE_SCHEMA=@MY_SCHEMA
AND T.TABLE_TYPE="VIEW";
This can be done. Following are the steps to setup the GUI
sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui
sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes
sudo /etc/init.d/ssh restart
In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:
sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server
Then run following commands and enter the login password for vnc connection:
su - awsgui
vncserver
vncserver -kill :1
vim /home/awsgui/.vnc/xstartup
Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads
exec sh /etc/X11/xinit/xinitrc.
When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.
Then start vnc server again.
vncserver
You can download xtightvncviewer
to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients
In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.
Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html
Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/
Port opening on console
sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT
If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.
vncserver
As it was mentioned, there is no direct equivalent, but very close approximation could be created with Java bytecode modifications (for both async/await-like instructions and underlying continuations implementation).
I'm working right now on a project that implements async/await on top of JavaFlow continuation library, please check https://github.com/vsilaev/java-async-await
No Maven mojo is created yet, but you may run examples with supplied Java agent. Here is how async/await code looks like:
public class AsyncAwaitNioFileChannelDemo {
public static void main(final String[] argv) throws Exception {
...
final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo();
final CompletionStage<String> result = demo.processFile("./.project");
System.out.println("Returned to caller " + LocalTime.now());
...
}
public @async CompletionStage<String> processFile(final String fileName) throws IOException {
final Path path = Paths.get(new File(fileName).toURI());
try (
final AsyncFileChannel file = new AsyncFileChannel(
path, Collections.singleton(StandardOpenOption.READ), null
);
final FileLock lock = await(file.lockAll(true))
) {
System.out.println("In process, shared lock: " + lock);
final ByteBuffer buffer = ByteBuffer.allocateDirect((int)file.size());
await( file.read(buffer, 0L) );
System.out.println("In process, bytes read: " + buffer);
buffer.rewind();
final String result = processBytes(buffer);
return asyncResult(result);
} catch (final IOException ex) {
ex.printStackTrace(System.out);
throw ex;
}
}
@async is the annotation that flags a method as asynchronously executable, await() is a function that waits on CompletableFuture using continuations and a call to "return asyncResult(someValue)" is what finalizes associated CompletableFuture/Continuation
As with C#, control flow is preserved and exception handling may be done in regular manner (try/catch like in sequentially executed code)
if
and grep -Eq
arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
echo 'second'
fi
where:
-q
prevents grep
from producing output, it just produces the exit status-E
enables extended regular expressionsI like this because:
case
One downside is that this is likely slower than case
since it calls an external grep
program, but I tend to consider performance last when using Bash.
case
is POSIX 7
Bash appears to follow POSIX by default without shopt
as mentioned by https://stackoverflow.com/a/4555979/895245
Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":
The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]
The format for the case construct is as follows:
case word in [(] pattern1 ) compound-list ;; [[(] pattern[ | pattern] ... ) compound-list ;;] ... [[(] pattern[ | pattern] ... ) compound-list] esac
and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?
, *
and []
.
const keyword available in javscript language but it does not support IE browser. Rest all browser supported.
The documentation is a little confusing when it comes to project pages, as opposed to user pages. It feels like you should have to do more, but actually the process is very easy.
It involves:
Your content will be served from a URL of the form http://nicholasjohnson.com.
Visiting http://www.nicholasjohnson.com will return a 301 redirect to the naked domain.
The path will be respected by the redirect, so traffic to http://www.nicholasjohnson.com/angular will be redirected to http://nicholasjohnson.com/angular.
You can have one project page per repository, so if your repos are open you can have as many as you like.
Here's the process:
For the A records, point @ to the following ip addresses:
@: 185.199.108.153
@: 185.199.109.153
@: 185.199.110.153
@: 185.199.111.153
These are the static Github IP addresses from which your content will be served.
For the CNAME record, point www to yourusername.github.io. Note the trailing full stop. Note also, this is the username, not the project name. You don't need to specify the project name yet. Github will use the CNAME file to determine which project to serve content from.
e.g.
www: forwardadvance.github.io.
The purpose of the CNAME is to redirect all www subdomain traffic to a GitHub page which will 301 redirect to the naked domain.
Here's a screenshot of the configuration I use for my own site http://nicholasjohnson.com:
Add a file called CNAME to your project root in the gh-pages branch. This should contain the domain you want to serve. Make sure you commit and push.
e.g.
nicholasjohnson.com
This file tells GitHub to use this repo to handle traffic to this domain.
Now wait 5 minutes, your project page should now be live.
$('[name="CheckboxName"]:checked').each(function () {
// do stuff
});
The PECL APD extension is used as follows:
<?php
apd_set_pprof_trace();
//rest of the script
?>
After, parse the generated file using pprofp
.
Example output:
Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace
14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
Warning: the latest release of APD is dated 2004, the extension is no longer maintained and has various compability issues (see comments).
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
The trick here is that you don't want to include the whole bootstrap. The issue is that email clients will ignore the media queries and process all the print styles which have a lot of !important statements.
Instead, you need to only include the specific parts of bootstrap that you need. My email.css.scss file looks like this:
@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";
@import 'bootstrap/normalize';
@import 'bootstrap/tables';
I'm sending files(array) using formData in vuejs
for me below code is working
if(this.requiredDocumentForUploads.length > 0) {
this.requiredDocumentForUploads.forEach(file => {
var name = file.attachment_type // attachment_type is using for naming
if(document.querySelector("[name=" + name + "]").files.length > 0) {
formData.append("requiredDocumentForUploadsNew[" + name + "]", document.querySelector("[name=" + name + "]").files[0])
}
})
}
I had same problem with a site on our direct admin hosted site. I added
DirectoryIndex index.php
as a custom httd extension (which adds code to a sites httpd
file) and the site then ran the index.php
by default.
Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time,
you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld .
Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch
They work equally well. Performance is about the same given a modern compiler.
I prefer if statements over case statements because they are more readable, and more flexible -- you can add other conditions not based on numeric equality, like " || max < min ". But for the simple case you posted here, it doesn't really matter, just do what's most readable to you.
If you're after serialization, but won't need the data in other programs, I strongly recommend the shelve
module. Think of it as a persistent dictionary.
myData = shelve.open('/path/to/file')
# Check for values.
keyVar in myData
# Set values
myData[anotherKey] = someValue
# Save the data for future use.
myData.close()
I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.
My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
I insert this code in my tag and it works correctly:
ng-show="!Contract.BuyerName.trim()" >
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
To me, handling exception can be seen as business rule. Obviously, the first approach is unacceptable. The second one is better one and it might be 100% correct way IF the context says so. Now, for example, you are developing an Outlook Addin. If you addin throws unhandled exception, the outlook user might now know it since the outlook will not destroy itself because of one plugin failed. And you have hard time to figure out what went wrong. Therefore, the second approach in this case, to me, it is a correct one. Beside logging the exception, you might decide to display error message to user - i consider it as a business rule.
To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().
How does system understand whether there's a file or a folder?
I guess, the file and folder entries are kept in a data structure and it's managed by the file system.
There is a tool usually used in MS Servers (as far as I can remember) called forfiles:
The link above contains help as well as a link to the microsoft download page.
Gradle wrapper needs to be built. Try running gradle wrapper --gradle-version 2.13
Remember to change 2.13 to your gradle version number. After running this command, you should see new scripts added to your project folder. You should be able to run the wrapper with ./gradlew build
to build your code. Please refer to this guid for more information https://spring.io/guides/gs/gradle/.
Through the Javascript SDK (v2.12 - April, 2017) you can get the details of the picture request this way:
FB.api("/" + uid + "/picture?redirect=0", function (response) {
console.log(response);
// prints the following:
//data: {
// height: 50
// is_silhouette: false
// url: "https://lookaside.facebook.com/platform/profilepic/?asid=…&height=50&width=50&ext=…&hash…"
// width: 50
//}
if (response && !response.error) {
// change the src attribute of img elements
[...document.getElementsByClassName('fb-user-img')].forEach(
i => i.src = response.data.url
);
// OR redirect to the URL above
location.assign(response.data.url);
}
});
For getting the JSON response the parameter redirect
with 0 (zero) as value is important since the request redirects to the image by default. You may still add other parameters in the same URL. Examples:
"/" + uid + "/picture?redirect=0&width=100&height=100"
: a 100x100 image will be returned;"/" + uid + "/picture?redirect=0&type=large"
: a 200x200 image is returned. Other possible type values include: small, normal, album, and square.I've doing it with a function. In this case I will only transform character variables to factor:
for (i in 1:ncol(data)){
if(is.character(data[,i])){
data[,i]=factor(data[,i])
}
}
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
Use ResponseEntity
instead of ResponseBody
. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:
The
HttpEntity
is similar to@RequestBody
and@ResponseBody
. Besides getting access to the request and response body,HttpEntity
(and the response-specific subclassResponseEntity
) also allows access to the request and response headers
The code will look like:
@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
String json = "jsonResponse";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
A .tex file should be a LaTeX source file.
If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.
Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.
Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.
You can also check out this question and answer for how to do it: How to compile a LaTeX document?
Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.
I think this is an easy way for adding a .gitignore file to an existing repository.
Prerequisite:
You need a browser to access your github account.
Steps
Have fun!
here is the link for a similar question
CSS select all previous siblings for a star rating
So I post my solution using bits of everyones responses and anyone can use it as reference and possibliy recommend improvements.
// Just to check input value
// Consts
const starRadios = document.querySelectorAll('input[name="rating"]');
// EventListeners
starRadios.forEach((radio) => radio.addEventListener('change', getStarRadioValue));
// Get star radio value
function getStarRadioValue(event) {
alert(event.target.value)
// Do something with it
};
_x000D_
.star-rating {
font-size: 1.5rem;
unicode-bidi: bidi-override;
direction: rtl;
text-align: left;
}
.star-rating.editable label:hover {
cursor: pointer;
}
.star-rating.editable .icon-star:hover,
.star-rating.editable .icon-star:hover ~ .icon-star {
background-color: #fb2727 !important;
}
.icon-star {
position: relative;
background-color: #72747d;
width: 32px;
height: 32px;
display: inline-block;
transition: background-color 0.3s ease;
}
.icon-star.filled {
background-color: #fb2727;
}
.icon-star > label {
display: inline-block;
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
.icon-star > label > input[type="radio"] {
position: absolute;
top: 0;
left: 0;
transform: translateY(50%) translateX(50%);
display: none;
}
_x000D_
<div class="star-rating editable">
<span class="icon-star">
<label>
<input type="radio" name="rating" value="5" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="4" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="3" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="2" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="1" />
</label>
</span>
</div>
_x000D_
#!/bin/sh
# Return relative path from canonical absolute dir path $1 to canonical
# absolute dir path $2 ($1 and/or $2 may end with one or no "/").
# Does only need POSIX shell builtins (no external command)
relPath () {
local common path up
common=${1%/} path=${2%/}/
while test "${path#"$common"/}" = "$path"; do
common=${common%/*} up=../$up
done
path=$up${path#"$common"/}; path=${path%/}; printf %s "${path:-.}"
}
# Return relative path from dir $1 to dir $2 (Does not impose any
# restrictions on $1 and $2 but requires GNU Core Utility "readlink"
# HINT: busybox's "readlink" does not support option '-m', only '-f'
# which requires that all but the last path component must exist)
relpath () { relPath "$(readlink -m "$1")" "$(readlink -m "$2")"; }
Above shell script was inspired by pini's (Thanks!). It triggers a bug in the syntax highlighting module of Stack Overflow (at least in my preview frame). So please ignore if highlighting is incorrect.
Some notes:
Except for the mentioned backslash sequences the last line of function "relPath" outputs pathnames compatible to python:
path=$up${path#"$common"/}; path=${path%/}; printf %s "${path:-.}"
Last line can be replaced (and simplified) by line
printf %s "$up${path#"$common"/}"
I prefer the latter because
Filenames can be directly appended to dir paths obtained by relPath, e.g.:
ln -s "$(relpath "<fromDir>" "<toDir>")<file>" "<fromDir>"
Symbolic links in the same dir created with this method do not have
the ugly "./"
prepended to the filename.
Code listing for regression tests (simply append it to the shell script):
############################################################################
# If called with 2 arguments assume they are dir paths and print rel. path #
############################################################################
test "$#" = 2 && {
printf '%s\n' "Rel. path from '$1' to '$2' is '$(relpath "$1" "$2")'."
exit 0
}
#######################################################
# If NOT called with 2 arguments run regression tests #
#######################################################
format="\t%-19s %-22s %-27s %-8s %-8s %-8s\n"
printf \
"\n\n*** Testing own and python's function with canonical absolute dirs\n\n"
printf "$format\n" \
"From Directory" "To Directory" "Rel. Path" "relPath" "relpath" "python"
IFS=
while read -r p; do
eval set -- $p
case $1 in '#'*|'') continue;; esac # Skip comments and empty lines
# q stores quoting character, use " if ' is used in path name
q="'"; case $1$2 in *"'"*) q='"';; esac
rPOk=passed rP=$(relPath "$1" "$2"); test "$rP" = "$3" || rPOk=$rP
rpOk=passed rp=$(relpath "$1" "$2"); test "$rp" = "$3" || rpOk=$rp
RPOk=passed
RP=$(python -c "import os.path; print os.path.relpath($q$2$q, $q$1$q)")
test "$RP" = "$3" || RPOk=$RP
printf \
"$format" "$q$1$q" "$q$2$q" "$q$3$q" "$q$rPOk$q" "$q$rpOk$q" "$q$RPOk$q"
done <<-"EOF"
# From directory To directory Expected relative path
'/' '/' '.'
'/usr' '/' '..'
'/usr/' '/' '..'
'/' '/usr' 'usr'
'/' '/usr/' 'usr'
'/usr' '/usr' '.'
'/usr/' '/usr' '.'
'/usr' '/usr/' '.'
'/usr/' '/usr/' '.'
'/u' '/usr' '../usr'
'/usr' '/u' '../u'
"/u'/dir" "/u'/dir" "."
"/u'" "/u'/dir" "dir"
"/u'/dir" "/u'" ".."
"/" "/u'/dir" "u'/dir"
"/u'/dir" "/" "../.."
"/u'" "/u'" "."
"/" "/u'" "u'"
"/u'" "/" ".."
'/u"/dir' '/u"/dir' '.'
'/u"' '/u"/dir' 'dir'
'/u"/dir' '/u"' '..'
'/' '/u"/dir' 'u"/dir'
'/u"/dir' '/' '../..'
'/u"' '/u"' '.'
'/' '/u"' 'u"'
'/u"' '/' '..'
'/u /dir' '/u /dir' '.'
'/u ' '/u /dir' 'dir'
'/u /dir' '/u ' '..'
'/' '/u /dir' 'u /dir'
'/u /dir' '/' '../..'
'/u ' '/u ' '.'
'/' '/u ' 'u '
'/u ' '/' '..'
'/u\n/dir' '/u\n/dir' '.'
'/u\n' '/u\n/dir' 'dir'
'/u\n/dir' '/u\n' '..'
'/' '/u\n/dir' 'u\n/dir'
'/u\n/dir' '/' '../..'
'/u\n' '/u\n' '.'
'/' '/u\n' 'u\n'
'/u\n' '/' '..'
'/ a b/å/?*/!' '/ a b/å/?/xäå/?' '../../?/xäå/?'
'/' '/A' 'A'
'/A' '/' '..'
'/ & / !/*/\\/E' '/' '../../../../..'
'/' '/ & / !/*/\\/E' ' & / !/*/\\/E'
'/ & / !/*/\\/E' '/ & / !/?/\\/E/F' '../../../?/\\/E/F'
'/X/Y' '/ & / !/C/\\/E/F' '../../ & / !/C/\\/E/F'
'/ & / !/C' '/A' '../../../A'
'/A / !/C' '/A /B' '../../B'
'/Â/ !/C' '/Â/ !/C' '.'
'/ & /B / C' '/ & /B / C/D' 'D'
'/ & / !/C' '/ & / !/C/\\/Ê' '\\/Ê'
'/Å/ !/C' '/Å/ !/D' '../D'
'/.A /*B/C' '/.A /*B/\\/E' '../\\/E'
'/ & / !/C' '/ & /D' '../../D'
'/ & / !/C' '/ & /\\/E' '../../\\/E'
'/ & / !/C' '/\\/E/F' '../../../\\/E/F'
'/home/p1/p2' '/home/p1/p3' '../p3'
'/home/p1/p2' '/home/p4/p5' '../../p4/p5'
'/home/p1/p2' '/work/p6/p7' '../../../work/p6/p7'
'/home/p1' '/work/p1/p2/p3/p4' '../../work/p1/p2/p3/p4'
'/home' '/work/p2/p3' '../work/p2/p3'
'/' '/work/p2/p3/p4' 'work/p2/p3/p4'
'/home/p1/p2' '/home/p1/p2/p3/p4' 'p3/p4'
'/home/p1/p2' '/home/p1/p2/p3' 'p3'
'/home/p1/p2' '/home/p1/p2' '.'
'/home/p1/p2' '/home/p1' '..'
'/home/p1/p2' '/home' '../..'
'/home/p1/p2' '/' '../../..'
'/home/p1/p2' '/work' '../../../work'
'/home/p1/p2' '/work/p1' '../../../work/p1'
'/home/p1/p2' '/work/p1/p2' '../../../work/p1/p2'
'/home/p1/p2' '/work/p1/p2/p3' '../../../work/p1/p2/p3'
'/home/p1/p2' '/work/p1/p2/p3/p4' '../../../work/p1/p2/p3/p4'
'/-' '/-' '.'
'/?' '/?' '.'
'/??' '/??' '.'
'/???' '/???' '.'
'/?*' '/?*' '.'
'/*' '/*' '.'
'/*' '/**' '../**'
'/*' '/***' '../***'
'/*.*' '/*.**' '../*.**'
'/*.???' '/*.??' '../*.??'
'/[]' '/[]' '.'
'/[a-z]*' '/[0-9]*' '../[0-9]*'
EOF
format="\t%-19s %-22s %-27s %-8s %-8s\n"
printf "\n\n*** Testing own and python's function with arbitrary dirs\n\n"
printf "$format\n" \
"From Directory" "To Directory" "Rel. Path" "relpath" "python"
IFS=
while read -r p; do
eval set -- $p
case $1 in '#'*|'') continue;; esac # Skip comments and empty lines
# q stores quoting character, use " if ' is used in path name
q="'"; case $1$2 in *"'"*) q='"';; esac
rpOk=passed rp=$(relpath "$1" "$2"); test "$rp" = "$3" || rpOk=$rp
RPOk=passed
RP=$(python -c "import os.path; print os.path.relpath($q$2$q, $q$1$q)")
test "$RP" = "$3" || RPOk=$RP
printf "$format" "$q$1$q" "$q$2$q" "$q$3$q" "$q$rpOk$q" "$q$RPOk$q"
done <<-"EOF"
# From directory To directory Expected relative path
'usr/p1/..//./p4' 'p3/../p1/p6/.././/p2' '../../p1/p2'
'./home/../../work' '..//././../dir///' '../../dir'
'home/p1/p2' 'home/p1/p3' '../p3'
'home/p1/p2' 'home/p4/p5' '../../p4/p5'
'home/p1/p2' 'work/p6/p7' '../../../work/p6/p7'
'home/p1' 'work/p1/p2/p3/p4' '../../work/p1/p2/p3/p4'
'home' 'work/p2/p3' '../work/p2/p3'
'.' 'work/p2/p3' 'work/p2/p3'
'home/p1/p2' 'home/p1/p2/p3/p4' 'p3/p4'
'home/p1/p2' 'home/p1/p2/p3' 'p3'
'home/p1/p2' 'home/p1/p2' '.'
'home/p1/p2' 'home/p1' '..'
'home/p1/p2' 'home' '../..'
'home/p1/p2' '.' '../../..'
'home/p1/p2' 'work' '../../../work'
'home/p1/p2' 'work/p1' '../../../work/p1'
'home/p1/p2' 'work/p1/p2' '../../../work/p1/p2'
'home/p1/p2' 'work/p1/p2/p3' '../../../work/p1/p2/p3'
'home/p1/p2' 'work/p1/p2/p3/p4' '../../../work/p1/p2/p3/p4'
EOF
First rule of threading - "Threading is fun"...
I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where
t.start()
is written but stillrun()
method is not executed rathermain()
method continues execution. So why is this happening?
This is exactly what should happen. When you call Thread#start
, the thread is created and schedule for execution, it might happen immediately (or close enough to it), it might not. It comes down to the thread scheduler.
This comes down to how the thread execution is scheduled and what else is going on in the system. Typically, each thread will be given a small amount of time to execute before it is put back to "sleep" and another thread is allowed to execute (obviously in multiple processor environments, more than one thread can be running at time, but let's try and keep it simple ;))
Threads may also yield
execution, allow other threads in the system to have chance to execute.
You could try
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
// Yield here
Thread.yield();
}
And it might make a difference to the way the threads run...equally, you could sleep
for a small period of time, but this could cause your thread to be overlooked for execution for a period of cycles (sometimes you want this, sometimes you don't)...
join()
method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??
The way you've stated the question is wrong...join
will wait for the Thread
it is called on to die before returning. For example, if you depending on the result of a Thread
, you could use join
to know when the Thread
has ended before trying to retrieve it's result.
Equally, you could poll the thread, but this will eat CPU cycles that could be better used by the Thread
instead...
as aside tip make sure your button is not subclass of any custom class in story board , in such a case your code best place should be in custom class it self cause code works only out of the custom class if your button is subclass of the default UIButton class and outlet of it , hope this may help anyone wonders why corner radios doesn't apply on my button from code .
Below code worked with me, it got the bitmap from the fileUri, and do the rotation fixing if required:
private fun getCapturedImage(selectedPhotoUri: Uri): Bitmap {
val bitmap = when {
Build.VERSION.SDK_INT < 28 -> MediaStore.Images.Media.getBitmap(
this.contentResolver,
selectedPhotoUri
)
else -> {
val source = ImageDecoder.createSource(this.contentResolver, selectedPhotoUri)
ImageDecoder.decodeBitmap(source)
}
}
// If the image is rotated, fix it
return when (ExifInterface(contentResolver.run { openInputStream(selectedPhotoUri) }).getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
ExifInterface.ORIENTATION_ROTATE_90 ->
Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, Matrix().apply {
postRotate(90F) }, true)
ExifInterface.ORIENTATION_ROTATE_180 ->
Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, Matrix().apply {
postRotate(180F) }, true)
ExifInterface.ORIENTATION_ROTATE_270 ->
Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, Matrix().apply {
postRotate(270F) }, true)
else -> bitmap
}
}
A space may only be encoded to "+" in the "application/x-www-form-urlencoded" content-type key-value pairs query part of an URL. In my opinion, this is a MAY, not a MUST. In the rest of URLs, it is encoded as %20.
In my opinion, it's better to always encode spaces as %20, not as "+", even in the query part of an URL, because it is the HTML specification (RFC-1866) that specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs (see paragraph 8.2.1. subparagraph 1.)
This way of encoding form data is also given in later HTML specifications. For example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
Here is a sample string in URL where the HTML specification allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses. In other cases, spaces should be encoded to %20. But since it's hard to correctly determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
The implementation depends on the programming language that you chose.
If your URL contains national characters, first encode them to UTF-8 and then percent-encode the result.
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:
<textarea name="comentarii" cols="36" rows="5" placeholder="Message>
From Xcode 9 and on you can take screenshot or record Video using simctl binary that you can find it here:
/Applications/Xcode.app/Contents/Developer/usr/bin/simctl
You can use it with xcrun to command the simulator in the command line.
For taking screenshot run this in command line:
xcrun simctl io booted screenshot
For recording video on the simulator using command line:
xcrun simctl io booted recordVideo fileName.videoType(e.g mp4/mov)
Note: You can use this command in any directory of your choice. The file will be saved in that directory.
Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.
Python Code
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()
Calling a Stored Procedure
dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )
C# Program to Check ODBC Connection
static void Main(string[] args)
{
string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;";
OdbcConnection cn = new OdbcConnection(connectionString);
cn.Open();
cn.Close();
}
Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.
To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.
Edit: I've copied the steps below - kudos to the original author of the link above.
I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)
Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps
pipeline {
agent none
stages {
stage ('Hello') {
agent any
steps {
echo 'Hello, '
sh '''#!/bin/bash
echo "Hello from bash"
echo "Who I'm $SHELL"
'''
}
}
}
}
The result of the above execution is
You can change youralias.conf
file like this code:
Alias /Quiz/ "h:/MyServer/Quiz/"
<Directory "h:/MyServer/Quiz/">
Options Indexes FollowSymLinks
AllowOverride all
<IfDefine APACHE24>
Require local
</IfDefine>
<IfDefine !APACHE24>
Order Deny,Allow
Deny from all
Allow from localhost ::1 127.0.0.1
</IfDefine>
</Directory>
if you're using sql server 2005, start sql server browser service first
Instead of calling every time AppendAllText()
you could think about opening the file once and then write the whole content once:
var file = @"C:\myOutput.csv";
using (var stream = File.CreateText(file))
{
for (int i = 0; i < reader.Count(); i++)
{
string first = reader[i].ToString();
string second = image.ToString();
string csvRow = string.Format("{0},{1}", first, second);
stream.WriteLine(csvRow);
}
}
Swift 5:
extension Dictionary {
/// Convert Dictionary to JSON string
/// - Throws: exception if dictionary cannot be converted to JSON data or when data cannot be converted to UTF8 string
/// - Returns: JSON string
func toJson() throws -> String {
let data = try JSONSerialization.data(withJSONObject: self)
if let string = String(data: data, encoding: .utf8) {
return string
}
throw NSError(domain: "Dictionary", code: 1, userInfo: ["message": "Data cannot be converted to .utf8 string"])
}
}
var dateFormat = 'YYYY-DD-MM HH:mm:ss';
var testDateUtc = moment.utc('2015-01-30 10:00:00');
var localDate = testDateUtc.local();
console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
From: http://georgovassilis.blogspot.ca/2015/10/spring-mvc-rest-controller-says-406.html
You've got this Spring @RestController and mapped a URL that contains an email as part of the URL path. You cunningly worked around the dot truncation issue [1] and you are ready to roll. And suddenly, on some URLs, Spring will return a 406 [2] which says that the browser requested a certain content type and Spring can't serialize the response to that content type. The point is, you've been doing Spring applications for years and you did all the MVC declarations right and you included Jackson and basically you are stuck. Even worse, it will spit that error out only on some emails in the URL path, most notably those ending in a ".com" domain.
@RequestMapping(value = "/agenda/{email:.+}", method = RequestMethod.GET)
public List<AgendaEntryDTO> checkAgenda(@PathVariable("email") String email)
The issue [3] is quite tricky: the application server performs some content negotiation and convinces Spring that the browser requested a "application/x-msdownload" content, despite that occurring nowhere in the request the browser actually submitted.
The solution is to specify a content negotiation manager for the web application context:
<mvc:annotation-driven enable-matrix-variables="true"
content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="false" />
<property name="parameterName" value="mediaType" />
<property name="ignoreAcceptHeader" value="false" />
<property name="useJaf" value="false" />
</bean>
Continuing with JoelAnair's answer:
For more robustness, use as follows:
var el = document.getElementById('targetFrame');
if(el.contentWindow)
{
el.contentWindow.targetFunction();
}
else if(el.contentDocument)
{
el.contentDocument.targetFunction();
}
Workd like charm :)
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
In your INSERT statements:
INSERT INTO employee(hans,germany) values(?,?)
You've got your values where your field names belong. Change it to be:
INSERT INTO employee(emp_name,emp_address) values(?,?)
If you were to run that statement from a SQL prompt, it would look like this:
INSERT INTO employee(emp_name,emp_address) values('hans','germany');
Note that you'd need to put single quotes around the string/varchar values.
Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();
Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.
Field search
('$options': 'i'
for case insensitive search)
db.users.aggregate([
{
$match: {
'email': { '$regex': '@gmail.com', '$options': 'i' }
}
}
]);
Full document search
(only works on fields indexed with a text index
db.articles.aggregate([
{
$match: { $text: { $search: 'brave new world' } }
}
])
To perform a linear regression between two vectors x
and y
follow these steps:
[p,err] = polyfit(x,y,1); % First order polynomial
y_fit = polyval(p,x,err); % Values on a line
y_dif = y - y_fit; % y value difference (residuals)
SSdif = sum(y_dif.^2); % Sum square of difference
SStot = (length(y)-1)*var(y); % Sum square of y taken from variance
rsq = 1-SSdif/SStot; % Correlation 'r' value. If 1.0 the correlelation is perfect
For x=[10;200;7;150]
and y=[0.001;0.45;0.0007;0.2]
I get rsq = 0.9181
.
Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html
This may be what you want. Settings -> Appearance & Behavior -> System Settings > Project Opening > Default Directory
It worked for me. I tried Android Studio 3.5.
Your bytes
object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes
to str
and replace the quotes. Another option is to use ast.literal_eval
; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,
import json
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
# Decode UTF-8 bytes to Unicode, and convert single quotes
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)
# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)
output
[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - -
[
{
"Classe": [
"Email addresses",
"Passwords"
],
"CreationDate": "2012-05-05",
"Date": "2016-05-21T21:35:40Z",
"Link": "http://some_link.com",
"LogoType": "png",
"Ref": 164611595
}
]
As Antti Haapala mentions in the comments, we can use ast.literal_eval
to convert my_bytes_value
to a Python list, once we've decoded it to a string.
from ast import literal_eval
import json
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)
Generally, this problem arises because someone has saved data by printing its Python repr
instead of using the json
module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.
The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude
option:
Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }
This will prevent the process from renaming any one file more than once.
It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
pno (*AddClient)(client_t *);
};
pno client_t_AddClient(client_t *self) { /* code */ }
int main()
{
client_t client;
client.AddClient = client_t_AddClient; // probably really done in some init fn
//code ..
client.AddClient(&client);
}
It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.
You have to validate the connection.
If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.
The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with
pool.setValidateConnectionOnBorrow(true);
But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with
if (connection == null || !((ValidConnection) connection).isValid())
See the Oracle documentation for further details.
David Wolever's solution is good, but
If you want to have signed angles you have to determine if a given pair is right or left handed (see wiki for further info).
My solution for this is:
def unit_vector(vector):
""" Returns the unit vector of the vector"""
return vector / np.linalg.norm(vector)
def angle(vector1, vector2):
""" Returns the angle in radians between given vectors"""
v1_u = unit_vector(vector1)
v2_u = unit_vector(vector2)
minor = np.linalg.det(
np.stack((v1_u[-2:], v2_u[-2:]))
)
if minor == 0:
raise NotImplementedError('Too odd vectors =(')
return np.sign(minor) * np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
It's not perfect because of this NotImplementedError
but for my case it works well. This behaviour could be fixed (cause handness is determined for any given pair) but it takes more code that I want and have to write.
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
In my experience, using the cross-join-with-a-where-clause syntax often produces a brain damaged execution plan, especially if you are using a Microsoft SQL product. The way that SQL Server attempts to estimate table row counts, for instance, is savagely horrible. Using the inner join syntax gives you some control over how the query is executed. So from a practical point of view, given the atavistic nature of current database technology, you have to go with the inner join.
The Podfile.lock
keeps track of the resolved versions of each Pod installed. If you want to double check that FlurrySDK is using 4.2.3, check that file.
Note: You should not edit this file. It is auto-generated when you run pod install
or pod update
Async HTTP client loopj vs. Volley
The specifics of my project are small HTTP REST requests, every 1-5 minutes.
I using an async HTTP client (1.4.1) for a long time. The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. Anyway, the new version of the library is not working for me: library inter exception cut chain of callbacks.
Reading all answers motivated me to try something new. I have chosen the Volley HTTP library.
After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley.
Maybe Retrofit is better than an async HTTP client? I need to try it. But I'm sure that Volley is not for me.
The best thing out there is Memory Analyzer (MAT), IntelliJ does not have any bundled heap dump analyzer.
If you pass the -v
flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will look in several places for the config file:
ansible.cfg
in the current directory where you ran ansible-playbook
~/.ansible.cfg
/etc/ansible/ansible.cfg
We can use a not famous built-in function; divmod:
>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338
php -f test.php
See the manual for full details of running PHP from the command line
You can add
from functools import reduce
before you use the reduce.
If you see then logical difference between these two is Comparator
in Java compare two objects provided to him, while Comparable
interface compares "this" reference with the object specified.
Comparable
in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable
interface.
If any class implement Comparable
interface in Java then collection of that object either List
or Array
can be sorted automatically by using Collections.sort()
or Array.sort()
method and object will be sorted based on there natural order defined by compareTo
method.
Objects which implement Comparable
in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet
, without specifying any Comparator
.
Use:
std::map<std::string, std::string>::const_iterator
instead:
std::map<std::string, std::string>::iterator
Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
Use hidden spans, one each for each of the parameters <%itemid%>
and <%itemname%>
and write their values inside them.
For example, the span for <%itemid%>
would look like <span id='itemid' style='display:none'><%itemid%></span>
and in the javascript function SelectSurveyItem
to pick the arguments from these spans' innerHTML
.
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
For Kali, you must use this code after the update.
$sudo python3 get-pip.py
or if you write this, it also works but not supported anymore. So don't use:
$sudo python get-pip.py
Vanilla:
window.addEventListener('scroll', function(ev) {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
console.log(distanceToTop);
});
Open your browser console and scroll your page to see the distance.
I've run into issues with Webclient.Downloadstring before. If you do, you can try this:
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
SELECT * FROM mysql.general_log WHERE command_type ='Query' LIMIT total;
I think this is the best way:
this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
This will not work, getElementById
will query only one element by time.
You can use document.querySelectorAll("#myCircle1, #myCircle2")
for querying more then one element.
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
Example:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];
// Now you can use cool array prototypes
elementsArray.forEach(element => {
console.log(element);
});
Another easy way if you have an array of IDs is to use the language to build your query, example:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
Corrected as of 25.06.2019:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Old From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.
// Support for string arguments
getClassNames('class1', 'class2');
// support for Object
getClassNames({class1: true, class2 : false});
// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
class5 : function() { return false; },
class6 : function() { return true; }
});
<div className={getClassNames({class1: true, class2 : false})} />
Are you running msysgit, or some other form of Windows git installation? msysgit is only one possible way to run git on Windows but it's probably also the simplest one. It's also the way recommended by the git website at http://git-scm.org/ .
If you are using msysgit, then you need to run the command in Git Bash, not in a standard Windows command line prompt. Git Bash is a prompt that is installed for you by msysgit, and is basically the most common Linux command line shell (bash) packaged for Windows to facilitate command line usage of git. msysgit should also install the ssh-keygen program in a place where it is accessible from Git Bash, but not necessarily from your usual Windows command line prompt.
The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.
The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.
Use oracle.jdbc.OracleDriver, not oracle.jdbc.driver.OracleDriver. You do not need to register it if the driver jar file is in the "WEB-INF\lib" directory, if you are using Tomcat. Save this as test.jsp and put it in your web directory, and redeploy your web app folder in Tomcat manager:
<%@ page import="java.sql.*" %>
<HTML>
<HEAD>
<TITLE>Simple JSP Oracle Test</TITLE>
</HEAD><BODY>
<%
Connection conn = null;
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@XXX.XXX.XXX.XXX:XXXX:dbName", "user", "password");
Statement stmt = conn.createStatement();
out.println("Connection established!");
}
catch (Exception ex)
{
out.println("Exception: " + ex.getMessage() + "");
}
finally
{
if (conn != null) {
try {
conn.close();
}
catch (Exception ignored) {
// ignore
}
}
}
%>
bufferedWriter.write(text + "\n");
This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:
bufferedWriter.write(text);
bufferedWriter.newline();
By default git revert
refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD
is in fact a merge commit.
If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.
Often this will be parent number one, for example if you were on master
and did git merge unwanted
and then decided to revert the merge of unwanted
. The first parent would be your pre-merge master
branch and the second parent would be the tip of unwanted
.
In this case you could do:
git revert -m 1 HEAD
Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...
Rejoice.
Even more, you can inherit generics :)
@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
return (T) somethingHolderMap.get(clazz);
}
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
Web Hosting Challenge
You have to remember that none of the machine configuration options are available if you are hosted on a shared server as many of us (smaller companies and individuals) are.
ASP.NET MVC Overhead
My site takes at least 30 seconds when it hasn't been hit in over 20 minutes (and the web app has been stopped). It is terrible.
Another Way to Test Performance
There's another way to test if it is your ASP.NET MVC start up or something else. Drop a normal HTML page on your site where you can hit it directly.
If the problem is related to ASP.NET MVC start up then the HTML page will render almost immediately even when the web app hasn't been started.
That's how I first recognized that the problem was in the ASP.NET MVC startup.
I loaded an HTML page at any time and it would load blazing fast. Then, after hitting that HTML page I'd hit one of my ASP.NET MVC URLs and I'd get the Chrome message "Waiting for raddev.us..."
Another Test With Helpful Script
After that I wrote a LINQPad (check out http://linqpad.net for more) script that would hit my web site every 8 minutes (less than the time for the app to unload -- which should be 20 minutes) and I let it run for hours.
While the script was running I hit my web site and every time my site came up blazingly fast. This gives me a good idea that most likely the slowness I was experiencing was because of ASP.NET MVC startup times.
Get LinqPad and you can run the following script -- just change the URL to your own and let it run and you can test this easily. Good luck.
NOTE: In LinqPad you'll need to press F4 and add a reference to System.Net to add the library which will retrieve your page.
ALSO : make sure you change the String URL variable to point at a URL that will load a route from your ASP.NET MVC site so the engine will run.
System.Timers.Timer webKeepAlive = new System.Timers.Timer();
Int64 counter = 0;
void Main()
{
webKeepAlive.Interval = 5000;
webKeepAlive.Elapsed += WebKeepAlive_Elapsed;
webKeepAlive.Start();
}
private void WebKeepAlive_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
webKeepAlive.Stop();
try
{
// ONLY the first time it retrieves the content it will print the string
String finalHtml = GetWebContent();
if (counter < 1)
{
Console.WriteLine(finalHtml);
}
counter++;
}
finally
{
webKeepAlive.Interval = 480000; // every 8 minutes
webKeepAlive.Start();
}
}
public String GetWebContent()
{
try
{
String URL = "http://YOURURL.COM";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
Console.WriteLine (String.Format("{0} : success",DateTime.Now));
return html;
}
catch (Exception ex)
{
Console.WriteLine (String.Format("{0} -- GetWebContent() : {1}",DateTime.Now,ex.Message));
return "fail";
}
}
try this, this javascript code to change text all time to click button.http://jsfiddle.net/V4u5X/2/
html code
<button class="SeeMore2">See More</button>
javascript
$('.SeeMore2').click(function(){
var $this = $(this);
$this.toggleClass('SeeMore2');
if($this.hasClass('SeeMore2')){
$this.text('See More');
} else {
$this.text('See Less');
}
});
Most common case of this error happening is using template that is generating the control then changing the way id
and/or name
are being generated by 'overriding' default template with something like
@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} )
and then forgetting to change ValidationMessageFor
to
@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] })
Hope this saves you some time.
In the special case that you are creating a new repository starting from an old repository that you used as template (Don't do this if this is not your case). Completely erase the git files of the old repository so you can start a new one:
rm -rf .git
And then restart a new git repository as usual:
git init
git add whatever.wvr ("git add --all" if you want to add all files)
git commit -m "first commit"
git remote add origin [email protected]:ppreyer/first_app.git
git push -u origin master
Wrap the code in $(document).ready()
method or $()
.
$(function(){
$('#content').click(function(e) {
alert(1);
});
});
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
There is a bitshift
trick I use if I want to to convert from bytes
to any other unit. If you do a right shift by 10
you basically shift it by an order (multiple).
Example:
5GB are 5368709120 bytes
print (5368709120 >> 10) # 5242880 kilobytes (kB)
print (5368709120 >> 20 ) # 5120 megabytes (MB)
print (5368709120 >> 30 ) # 5 gigabytes (GB)
- (void)viewWillAppear:(BOOL)animated
{
[self setDetailViewNavigationBar];
}
-(void)setDetailViewNavigationBar
{
self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
[self setNavigationBarRightButton];
[self setNavigationBarBackButton];
}
-(void)setNavigationBarBackButton// using custom button
{
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@" Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];
self.navigationItem.leftBarButtonItem = leftButton;
}
- (void)onClickLeftButton:(id)sender
{
NSLog(@"onClickLeftButton");
}
-(void)setNavigationBarRightButton
{
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
- (void)onClickrighttButton:(id)sender
{
NSLog(@"onClickrighttButton");
}
The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html
FORCE INDEX
goes right after the table reference:
SELECT * FROM (
SELECT owner_id,
product_id,
start_time,
price,
currency,
name,
closed,
active,
approved,
deleted,
creation_in_progress
FROM db_products FORCE INDEX (products_start_time)
ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
AND resultstable.active = 1
AND resultstable.approved = 1
AND resultstable.deleted = 0
AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC
WARNING:
If you're using ORDER BY
before GROUP BY
to get the latest entry per owner_id
, you're using a nonstandard and undocumented behavior of MySQL to do that.
There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.
Search the greatest-n-per-group tag for many explanations of better solutions for this type of query.
I needed to do a query to get me all groups with a managedBy value set (not empty) and this gave some nice results:
(!(!managedBy=*))
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
$value = "he doesn't work for me";
$new_value = str_replace("'", "''", "$value"); // it looks like " ' " , " ' ' "
INSERT INTO exampleTbl (`column`) VALUES('$new_value')
It can also happen if you don't properly supply your list of parameters. Here's what I was doing:
java -jar [email protected] testing_subject file.txt test_send_emails.jar
Instead of the correct version:
java -jar test_send_emails.jar [email protected] testing_subject file.txt
Did you consider using nginx (or other event based web server) instead of apache?
nginx shall allow higher number of connections and consume much less resources (as it is event based and does not create separate process per connection). Anyway, you will need some processes, doing real work (like WSGI servers or so) and if they stay on the same server as the front end web server, you only shift the performance problem to a bit different place.
Latest apache version shall allow similar solution (configure it in event based manner), but this is not my area of expertise.
If you're using sqlplus in a shell, like bash you can run the shell's clear command from sqlplus:
SQL> host clear
you can abbreviate of course:
SQL> ho clear
This is my work around:
1) Add a wrapper div to the recaptcha div.
<div id="recaptcha-wrapper"><div class="g-recaptcha" data-sitekey="..."></div></div>
2) Add javascript/jquery code.
$(function(){
// global variables
captchaResized = false;
captchaWidth = 304;
captchaHeight = 78;
captchaWrapper = $('#recaptcha-wrapper');
captchaElements = $('#rc-imageselect, .g-recaptcha');
resizeCaptcha();
$(window).on('resize', function() {
resizeCaptcha();
});
});
function resizeCaptcha() {
if (captchaWrapper.width() >= captchaWidth) {
if (captchaResized) {
captchaElements.css('transform', '').css('-webkit-transform', '').css('-ms-transform', '').css('-o-transform', '').css('transform-origin', '').css('-webkit-transform-origin', '').css('-ms-transform-origin', '').css('-o-transform-origin', '');
captchaWrapper.height(captchaHeight);
captchaResized = false;
}
} else {
var scale = (1 - (captchaWidth - captchaWrapper.width()) * (0.05/15));
captchaElements.css('transform', 'scale('+scale+')').css('-webkit-transform', 'scale('+scale+')').css('-ms-transform', 'scale('+scale+')').css('-o-transform', 'scale('+scale+')').css('transform-origin', '0 0').css('-webkit-transform-origin', '0 0').css('-ms-transform-origin', '0 0').css('-o-transform-origin', '0 0');
captchaWrapper.height(captchaHeight * scale);
if (captchaResized == false) captchaResized = true;
}
}
3) Optional: add some styling if needed.
#recaptcha-wrapper {
text-align:center;
margin-bottom:15px;
}
.g-recaptcha {
display:inline-block;
}
Actually more sane sources are provided by http://suckless.org look at their sbase
repository:
git clone git://git.suckless.org/sbase
They are clearer, smarter, simpler and suckless, eg ls.c
has just 369 LOC
After that it will be easier to understand more complicated GNU code.
The picture you showd in the question is actually a chart made using JavaScript. It is actually very easy to plot multi-axis chart using JavaScript with the help of 3rd party libraries like HighChart.js or D3.js. Here I propose to use the Funfun Excel add-in which allows you to use JavaScript directly in Excel so you could plot chart like you've showed easily in Excel. Here I made an example using Funfun in Excel.
You could see in this chart you have one axis of Rainfall at the left side while two axis of Temperature and Sea-pressure level at the right side. This is also a combination of line chart and bar chart for different datasets. In this example, with the help of the Funfun add-in, I used HighChart.js to plot this chart.
Funfun also has an online editor in which you could test your JavaScript code with you data. You could check the detailed code of this example on the link below.
https://www.funfun.io/1/#/edit/5a43b416b848f771fbcdee2c
Edit: The content on the previous link has been changed so I posted a new link here. The link below is the original link https://www.funfun.io/1/#/edit/5a55dc978dfd67466879eb24
If you are satisfied with the result you achieved in the online editor, you could easily load the result into you Excel using the URL above. Of couse first you need to insert the Funfun add-in from Insert - My add-ins. Here are some screenshots showing how you could do this.
Disclosure: I'm a developer of Funfun
A solution for me:
$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {
#Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference
Or use try-catch
try {
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
}
catch {
}
I wanted to replicate Unix/Linux's cp -r
as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e
Copies directories and subdirectories, including empty ones.
/k
Copies attributes. Normal Xcopy will reset read-only attributes.
/h
Copies hidden and system files also.
/i
If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat
) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q
Quiet. Do not display file names while copying.
/b
Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o
Copies directory and file ACLs. (requires UAC admin)
I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angular project. They have taken care of every possible cases.
/* Seach in Object */
var comparator = function(obj, text) {
if (obj && text && typeof obj === 'object' && typeof text === 'object') {
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
comparator(obj[objKey], text[objKey])) {
return true;
}
}
return false;
}
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};
var search = function(obj, text) {
if (typeof text == 'string' && text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return comparator(obj, text);
case "object":
switch (typeof text) {
case "object":
return comparator(obj, text);
default:
for (var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
break;
}
return false;
case "array":
for (var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.
Root could not erase a file.
I did my research. Turns out there's something called an immutable bit.
# lsattr /path/file
----i-------- /path/file
#
This bit being configured prevents even root from modifying/removing it.
To remove this I did:
# chattr -i /path/file
After that I could rm the file.
In reverse, it's a neat trick to know if you have something you want to keep from being gone.
:)
I don't actually find any of the presented solutions here to be fully complete so I'll add my own. Nothing new here. You can stitch this together from the other presented solutions plus various comments.
There are at least two things you'll have to make sure:
Make sure you pass the table name to the getTables()
method,
rather than passing a null value. In the first case you let the
database server filter the result for you, in the second you request
a list of all tables from the server and then filter the list
locally. The former is much faster if you are only searching for a
single table.
Make sure to check the table name from the resultset with an equals
match. The reason is that the getTables()
does pattern matching on
the query for the table and the _
character is a wildcard in SQL.
Suppose you are checking for the existence of a table named
EMPLOYEE_SALARY
. You'll then get a match on EMPLOYEESSALARY
too
which is not what you want.
Ohh, and do remember to close those resultsets. Since Java 7 you would want to use a try-with-resources statement for that.
Here's a complete solution:
public static boolean tableExist(Connection conn, String tableName) throws SQLException {
boolean tExists = false;
try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
while (rs.next()) {
String tName = rs.getString("TABLE_NAME");
if (tName != null && tName.equals(tableName)) {
tExists = true;
break;
}
}
}
return tExists;
}
You may want to consider what you pass as the types
parameter (4th parameter) on your getTables()
call. Normally I would just leave at null
because you don't want to restrict yourself. A VIEW is as good as a TABLE, right? These days many databases allow you to update through a VIEW so restricting yourself to only TABLE type is in most cases not the way to go. YMMV.
Essentially, it depends on how you think of a string.
I always use utf8_bin because of the problem highlighted by Guus. In my opinion, as far as the database should be concerned, a string is still just a string. A string is a number of UTF-8 characters. A character has a binary representation so why does it need to know the language you're using? Usually, people will be constructing databases for systems with the scope for multilingual sites. This is the whole point of using UTF-8 as a character set. I'm a bit of a pureist but I think the bug risks heavily outweigh the slight advantage you may get on indexing. Any language related rules should be done at a much higher level than the DBMS.
In my books "value" should never in a million years be equal to "valúe".
If I want to store a text field and do a case insensitive search, I will use MYSQL string functions with PHP functions such as LOWER() and the php function strtolower().
One solution might be to change the i18n default error format:
en:
errors:
format: "%{message}"
Default is format: %{attribute} %{message}
I would like to propose the usage of string templates. Just place the string to be replaced in a dictionary and all is set! Example from docs.python.org
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
From office 2010, we won't be able to use the common dialog box control, so it's nice to use the Application object to get the desired results.
Here I got a text box and Command button - paste the following code under the command button click event, which will open the file dialog box and add the File name to the Text box.
Dim sFileName As String
sFileName = Application.GetOpenFilename("MS Excel (*.xlsx), *.xls")
TextBox1.Text = sFileName
Just an addition to the answer of @phantomlimb,
while View.generateViewId()
require API Level >= 17,
this tool is compatibe with all API.
according to current API Level,
it decide weather using system API or not.
so you can use ViewIdGenerator.generateViewId()
and View.generateViewId()
in the
same time and don't worry about getting same id
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
/**
* {@link View#generateViewId()}??API Level >= 17,??????????API Level
* <p>
* ??????API Level,?????{@link View#generateViewId()},???????{@link View#generateViewId()}
* ??,???????Id??
* <p>
* =============
* <p>
* while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
* <p>
* according to current API Level, it decide weather using system API or not.<br>
* so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
* same time and don't worry about getting same id
*
* @author [email protected]
*/
public class ViewIdGenerator {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
@SuppressLint("NewApi")
public static int generateViewId() {
if (Build.VERSION.SDK_INT < 17) {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF)
newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
} else {
return View.generateViewId();
}
}
}
You can try:
WHERE created_date BETWEEN CURRENT_TIMESTAMP-180 AND CURRENT_TIMESTAMP
The $.fn.equals(...)
solution is probably the cleanest and most elegant one.
I have tried something quick and dirty like this:
JSON.stringify(a) == JSON.stringify(b)
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.
https://developers.google.com/web/updates/2017/09/abortable-fetch
https://dom.spec.whatwg.org/#aborting-ongoing-activities
// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;
// fetch as usual
fetch(url, { signal }).then(response => {
...
}).catch(e => {
// catch the abort if you like
if (e.name === 'AbortError') {
...
}
});
// when you want to abort
controller.abort();
works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.
on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'
// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
Since hashcode always returns a number its always fast to retrieve an object using a number rather than an alphabetic key. How will it do? Assume we created a new object by passing some value which is already available in some other object. Now the new object will return the same hash value as of another object because the value passed is same. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.
You can always set the options, based on this page you can set, to get rid of the seconds, something like this
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.
Look at the length of the string after replacing the sequence
declare @s varchar(10) = 'aabaacaa'
select len(@s) - len(replace(@s, 'a', ''))
>>6
You can view which modules (compiled in) are available via terminal through php -m
Depends, if i remember correctly i think asp.net won't render the html object out when you set visible to false.
If you want to be able to control it from the client side, then you better just include the css value to set it invisible rather than using visible =false.
If you're using create-react-app, you can simply add a .env
file containing
NODE_PATH=src/
Source: https://medium.com/@ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d
I had the same problem. To fix it in Jboss 7 AS, I copy the oracle driver jar file to Jboss module folder. Example: ../jboss-as-7.1.1.Final/modules/org/hibernate/main
.
You also need to change "module.xml"
<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
<resources>
<resource-root path="hibernate-core-4.0.1.Final.jar"/>
<resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
<resource-root path="hibernate-entitymanager-4.0.1.Final.jar"/>
<resource-root path="hibernate-infinispan-4.0.1.Final.jar"/>
<resource-root path="ojdbc6.jar"/>
</resources>
<dependencies>
<module name="asm.asm"/>
<module name="javax.api"/>
<module name="javax.persistence.api"/>
<module name="javax.transaction.api"/>
<module name="javax.validation.api"/>
<module name="org.antlr"/>
<module name="org.apache.commons.collections"/>
<module name="org.dom4j"/>
<module name="org.infinispan" optional="true"/>
<module name="org.javassist"/>
<module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
<module name="org.jboss.logging"/>
<module name="org.hibernate.envers" services="import" optional="true"/>
</dependencies>
From a file:
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)
The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.
The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER
after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName
, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier
This is a simiple example:
use example
go
create table Test1 (
id int primary key,
item uniqueidentifier,
inserted_at datetime
)
go
create table Test2 (
id int primary key,
inserted_at datetime
)
go
alter table Test2 add item uniqueidentifier;
go
--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());
insert into Test2 select * from Test1;
select * from Test1;
select * from Test2;
The error message is:
Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime
example of textarea for disable the resize option
<textarea CLASS="foo"></textarea>
<style>
textarea.foo
{
resize:none;
}
</style>
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
I recommend Logo (aka the turtle) to get the basic concepts down. It provides a good sandbox with immediate graphical feedback, and you can demostrate loops, variables, functions, conditionals, etc. This page provides an excellent tutorial.
After Logo, move to Python or Ruby. I recommend Python, as it's based on ABC, which was invented for the purpose of teaching programming.
When teaching programming, I must second EHaskins's suggestion of simple projects and then complex projects. The best way to learn is to start with a definite outcome and a measurable milestone. It keeps the lessons focused, allows the student to build skills and then build on those skills, and gives the student something to show off to friends. Don't underestimate the power of having something to show for one's work.
Theoretically, you can stick with Python, as Python can do almost anything. It's a good vehicle to teach object-oriented programming and (most) algorithms. You can run Python in interactive mode like a command line to get a feel for how it works, or run whole scripts at once. You can run your scripts interpreted on the fly, or compile them into binaries. There are thousands of modules to extend the functionality. You can make a graphical calculator like the one bundled with Windows, or you can make an IRC client, or anything else.
XKCD describes Python's power a little better:
You can move to C# or Java after that, though they don't offer much that Python doesn't already have. The benefit of these is that they use C-style syntax, which many (dare I say most?) languages use. You don't need to worry about memory management yet, but you can get used to having a bit more freedom and less handholding from the language interpreter. Python enforces whitespace and indenting, which is nice most of the time but not always. C# and Java let you manage your own whitespace while remaining strongly-typed.
From there, the standard is C or C++. The freedom in these languages is almost existential. You are now in charge of your own memory management. There is no garbage collection to help you. This is where you teach the really advanced algorithms (like mergesort and quicksort). This is where you learn why "segmentation fault" is a curse word. This is where you download the source code of the Linux kernel and gaze into the Abyss. Start by writing a circular buffer and a stack for string manipulation. Then work your way up.
And note that since Python types are only checked at runtime you can have code like:
if True:
x = 2
y = 4
else:
x = "One"
y = "Two"
print(x + y)
But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.
On Mac OS you have to press: CMD+ALT+I
In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)
Replacing this line:
with open('filename', 'w') as f:
With this:
with open('filename', 'w', encoding='utf-8') as f:
The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.
import java.util.Scanner; //import the framework
Scanner input = new Scanner(System.in); //opens a scanner, keyboard
System.out.print("Enter a number: "); //prompt the user
int myInt = input.nextInt(); //store the input from the user
Let me know if you have any questions. Fairly self-explanatory. I commented the code so you can read it. :)
Getting the old foreign key check state and sql mode are best way to truncate / Drop the table as Mysql Workbench do while synchronizing model to database.
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;`
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP TABLE TABLE_NAME;
TRUNCATE TABLE_NAME;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
On Linux I also notice that :
Interruption of system calls and library functions by signal handlers
If a signal handler is invoked while a system call or library function call is blocked, then either:
the call is automatically restarted after the signal handler returns; or
the call fails with the error EINTR.
... The details vary across UNIX systems; below, the details for Linux.
If a blocked call to one of the following interfaces is interrupted by a signal handler, then the call is automatically restarted after the signal handler returns if the SA_RESTART flag was used; otherwise the call fails with the error EINTR:
- read(2), readv(2), write(2), writev(2), and ioctl(2) calls on "slow" devices.
.....
The following interfaces are never restarted after being interrupted by a signal handler, regardless of the use of SA_RESTART; they always fail with the error EINTR when interrupted by a signal handler:
"Input" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): accept(2), recv(2), recvfrom(2), recvmmsg(2) (also with a non-NULL timeout argument), and recvmsg(2).
"Output" socket interfaces, when a timeout (SO_RCVTIMEO) has been set on the socket using setsockopt(2): connect(2), send(2), sendto(2), and sendmsg(2).
Check man 7 signal
for more details.
A simple usage would be use signal to avoid recvfrom
blocking indefinitely.
An example from APUE:
#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>
#define BUFLEN 128
#define TIMEOUT 20
void
sigalrm(int signo)
{
}
void
print_uptime(int sockfd, struct addrinfo *aip)
{
int n;
char buf[BUFLEN];
buf[0] = 0;
if (sendto(sockfd, buf, 1, 0, aip->ai_addr, aip->ai_addrlen) < 0)
err_sys("sendto error");
alarm(TIMEOUT);
//here
if ((n = recvfrom(sockfd, buf, BUFLEN, 0, NULL, NULL)) < 0) {
if (errno != EINTR)
alarm(0);
err_sys("recv error");
}
alarm(0);
write(STDOUT_FILENO, buf, n);
}
int
main(int argc, char *argv[])
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;
int sockfd, err;
struct sigaction sa;
if (argc != 2)
err_quit("usage: ruptime hostname");
sa.sa_handler = sigalrm;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGALRM, &sa, NULL) < 0)
err_sys("sigaction error");
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_DGRAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(argv[1], "ruptime", &hint, &ailist)) != 0)
err_quit("getaddrinfo error: %s", gai_strerror(err));
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
if ((sockfd = socket(aip->ai_family, SOCK_DGRAM, 0)) < 0) {
err = errno;
} else {
print_uptime(sockfd, aip);
exit(0);
}
}
fprintf(stderr, "can't contact %s: %s\n", argv[1], strerror(err));
exit(1);
}
In "classic" C language (C89/90) when you call an undeclared function, C assumes that it returns an int
and also attempts to derive the types of its parameters from the types of the actual arguments (no, it doesn't assume that it has no parameters, as someone suggested before).
In your specific example the compiler would look at do_something(dest, src)
call and implicitly derive a declaration for do_something
. The latter would look as follows
int do_something(char *, char *)
However, later in the code you explicitly declare do_something
as
char *do_something(char *, const char *)
As you can see, these declarations are different from each other. This is what the compiler doesn't like.
A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.
This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:
binary - decimal
000 - 0.000
001 - 0.125
010 - 0.250
011 - 0.375
100 - 0.500
101 - 0.625
110 - 0.750
111 - 0.875
But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4??
nor 0.9??
, and yet to display the full accuracy, we require 3 decimal digits.
tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).
I run my application with Java 8 and Java 8 brought security certificate onto its trust store. Then I switched to Java 7 and added the following into VM options:
-Djavax.net.ssl.trustStore=C:\<....>\java8\jre\lib\security\cacerts
Simply I pointed to the location where a certificate is.
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2
that aren't in array1
. It sounds like you're asking is array1 a subset of array2?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true
Null is not an instance of any class.
However, you can assign null to variables of any (object or array) type:
// this is false
boolean nope = (null instanceof String);
// but you can still use it as a String
String x = null;
"abc".startsWith(null);
It is now possible to achieve that in Flutter 1.5 and Dart 2.3 by using a for element in your collection.
var list = ["one", "two", "three", "four"];
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for(var item in list ) Text(item)
],
),
This will display four Text widgets containing the items in the list.
NB. No braces around the for loop and no return keyword.
By convention, in Python world, the shortcut for numpy
is np
, so:
In [1]: import numpy as np
In [2]: a = np.array([[1,2],[3,4]])
In Numpy, dimension, axis/axes, shape are related and sometimes similar concepts:
In Mathematics/Physics, dimension or dimensionality is informally defined as the minimum number of coordinates needed to specify any point within a space. But in Numpy, according to the numpy doc, it's the same as axis/axes:
In Numpy dimensions are called axes. The number of axes is rank.
In [3]: a.ndim # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2
the nth coordinate to index an array
in Numpy. And multidimensional arrays can have one index per axis.
In [4]: a[1,0] # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3 # which results in 3 (locate at the row 1 and column 0, 0-based index)
describes how many data (or the range) along each available axis.
In [5]: a.shape
Out[5]: (2, 2) # both the first and second axis have 2 (columns/rows/pages/blocks/...) data
Starting with Sql Server 2012: string concatenation function CONCAT
converts to string implicitly. Therefore, another option is
SELECT Id AS 'PatientId',
CONCAT(ParentId,'') AS 'ParentId'
FROM Patients
CONCAT
converts null
values to empty strings.
Some will consider this hacky, because it merely exploits a side effect of a function while the function itself isn't required for the task in hand.
For anyone who has this problem as of Android Studio 1.4, I got it to work by creating a module within the project that contains 2 things.
build.gradle with the following contents:
configurations.create("default")
artifacts.add("default", file('facebook-android-sdk-4.7.0.aar'))
the aar file (in this example 'facebook-android-sdk-4.7.0.aar')
Then include the new library as a module dependency. Now you can use a built aar without including the sources within the project.
Credit to Facebook for this hack. I found the solution while integrating the Android SDK into a project.
To break a loop, use break
instead of return
.
Or put the loop or control construct into a function, only functions can return values.
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
You can initialize a default header axios.defaults.headers
axios.defaults.headers = {
'Content-Type': 'application/json',
Authorization: 'myspecialpassword'
}
axios.post('https://myapi.com', { data: "hello world" })
.then(response => {
console.log('Response', response.data)
})
.catch(e => {
console.log('Error: ', e.response.data)
})
I was in the same place as you, finally I found a neat answer :
<form action="xx/xx" method="POST">
<input type="hidden" name="what you want" value="what you want">
<input type="image" src="xx.xx">
</form>
I know this question is too old, but still, I think this approach would be cleaner:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
UPDATE
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
Then you should use:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
%W
and %w
allow you to create an Array of strings without using quotes and commas.
Specify paths
--app
--one
one.module.ts
--services
--two
two.module.ts
--services
Create Service with new folder in module ONE
ng g service one/services/myNewServiceFolderName/serviceOne --module one/one
--one
one.module.ts // service imported and added to providers.
--services
--myNewServiceFolderName
serviceOne.service.ts
serviceOne.service.spec.ts
You can also use search function without parameters:
jQuery("#id").autocomplete("search", "");
You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).
select
if(
fieldA is NULL,
if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
) as maxValue
You can change NULL to your preferred default value (if both values is NULL).
You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.
Example:
DataTable sourceTable = GridAttendence.DataSource as DataTable;
DataView view = new DataView(sourceTable);
string[] sortData = ViewState["sortExpression"].ToString().Trim().Split(' ');
if (e.SortExpression == sortData[0])
{
if (sortData[1] == "ASC")
{
view.Sort = e.SortExpression + " " + "DESC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
Based on Dirk Stöcker's answer, here's a neat wrapper function for Python 3's print function. Use it just like you would use print.
As an added bonus, compared to the other answers, this won't print your text as a bytearray ('b"content"'), but as normal strings ('content'), because of the last decode step.
def uprint(*objects, sep=' ', end='\n', file=sys.stdout):
enc = file.encoding
if enc == 'UTF-8':
print(*objects, sep=sep, end=end, file=file)
else:
f = lambda obj: str(obj).encode(enc, errors='backslashreplace').decode(enc)
print(*map(f, objects), sep=sep, end=end, file=file)
uprint('foo')
uprint(u'Antonín Dvorák')
uprint('foo', 'bar', u'Antonín Dvorák')