This question is very, very, very old, but as a trick in the future, I recommend something like this:
.element{
box-shadow: 0px 0px 10px #232931;
}
.container{
height: 100px;
width: 100px;
overflow: hidden;
}
Basically, you have a box shadow and then wrapping the element in a div with its overflow set to hidden. You'll need to adjust the height, width, and even padding of the div to only show the left box shadow, but it works. See here for an example If you look at the example, you can see how there's no other shadows, but only a black left shadow. Edit: this is a retake of the same screen shot, in case some one thinks that I just cropped out the right. You can find it here
Download java-json.jar from here, which contains org.json.JSONArray
http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip
nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.
SELECT company
, workflow
, MIN(date)
FROM workflowTable
GROUP BY company
, workflow
There is pretty concise and easy way:
Response.Write("<script>alert('Your text');</script>");
Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}
Reference:
found a way:
$albums = $facebook->api('/' . $user_id . '/albums');
foreach($albums['data'] as $album){
if ($album['name'] == "Profile Pictures"){
$photos = $facebook->api('/' . $album['id'] . '/photos');
$profile_pic = $photos['data'][0]['source'];
break;
}
}
You could use the **\**
character before the value you want to escape e.g
insert into msglog(recipient) values('Mr. O\'riely')
select * from msglog where recipient = 'Mr. O\'riely'
you could also use tig for a nice, ncurses-based git repository browser. To view history of a file:
tig path/to/file
This could be accomplished with a single line of code:
IF OBJECT_ID('tempdb..#tempTableName') IS NOT NULL DROP TABLE #tempTableName;
I am assuming that you have enough permissions to create this directory.
To fix your problem, you can either ssh to some other location:
ssh [email protected]
and accept new key - it will create directory ~/.ssh
and known_hosts
underneath, or simply create it manually using
mkdir ~/.ssh
chmod 700 ~/.ssh
Note that chmod 700
is an important step!
After that, ssh-keygen should work without complaints.
Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
Below code is using com.google.gson.JsonArray
.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
You can use gridspec
and figure
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
TL;DR
git reset
resets Staging to the last commit. Use--hard
to also reset files in your Working directory to the last commit.
LONGER VERSION
But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset
in the context of undoing changes. E.g. see this:
If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.
From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset
and this
On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations
Your question is not 100% clear, but I'm assuming you want to find every piece of text inside [P][/P]
tags:
>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']
You can remove the time part of a date by using TRUNC
.
select field,datetime_field
from database
where datetime_field >= trunc(sysdate-1,'DD');
That query will give you all rows with dates starting from yesterday. Note the second argument to trunc()
. You can use this to truncate any part of the date.
If your datetime_fied contains '2011-05-04 08:23:54'
, the following date will be returned
trunc(datetime_field, 'HH24') => 2011-05-04 08:00:00
trunc(datetime_field, 'DD') => 2011-05-04 00:00:00
trunc(datetime_field, 'MM') => 2011-05-01 00:00:00
trunc(datetime_field, 'YYYY') => 2011-00-01 00:00:00
<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
Add above dependency in pom.xml file
Ah yes. Welcome to Asynchronous execution.
Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.
Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
Replication is not very hard to create.
Here's some good tutorials:
http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication
Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):
This way, you will avoid errors.
For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.
You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.
NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).
I would recommend to monitor your servers to make sure everything is fine.
Let me know if you need additional help
use "x".ord for a single character or "xyz".sum for a whole string.
When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.
On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.
Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output).
Get in touch with your inner OOP and you can never go wrong!
Anyone coming here:
Remove all migrations Remove db.sqlite file
redo migrations
Based on Pumbaa80's answer I have modified the code to use the console.log colours (working on Chrome for sure) and not HTML. Output can be seen inside console. You can edit the _variables inside the function adding some more styling.
function JSONstringify(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, '\t');
}
var
arr = [],
_string = 'color:green',
_number = 'color:darkorange',
_boolean = 'color:blue',
_null = 'color:magenta',
_key = 'color:red';
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var style = _number;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
style = _key;
} else {
style = _string;
}
} else if (/true|false/.test(match)) {
style = _boolean;
} else if (/null/.test(match)) {
style = _null;
}
arr.push(style);
arr.push('');
return '%c' + match + '%c';
});
arr.unshift(json);
console.log.apply(console, arr);
}
Here is a bookmarklet you can use:
javascript:function JSONstringify(json) {if (typeof json != 'string') {json = JSON.stringify(json, undefined, '\t');}var arr = [],_string = 'color:green',_number = 'color:darkorange',_boolean = 'color:blue',_null = 'color:magenta',_key = 'color:red';json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {var style = _number;if (/^"/.test(match)) {if (/:$/.test(match)) {style = _key;} else {style = _string;}} else if (/true|false/.test(match)) {style = _boolean;} else if (/null/.test(match)) {style = _null;}arr.push(style);arr.push('');return '%c' + match + '%c';});arr.unshift(json);console.log.apply(console, arr);};void(0);
Usage:
var obj = {a:1, 'b':'foo', c:[false,null, {d:{e:1.3e5}}]};
JSONstringify(obj);
Edit: I just tried to escape the % symbol with this line, after the variables declaration:
json = json.replace(/%/g, '%%');
But I find out that Chrome is not supporting % escaping in the console. Strange... Maybe this will work in the future.
Cheers!
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language, using either the str.format()
method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
of f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with listview:
This solution worked for me
;(function($){ // your code })(jQuery);
Move your code inside the closure and use $ instead of jQuery
I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma
after seraching too much
static void Main()
{
double[] array = new double[6];
Console.WriteLine("Please Sir Enter 6 Floating numbers");
for (int i = 0; i < 6; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
double average = sum / 6;
Console.WriteLine("===============================================");
Console.WriteLine("The Values you've entered are");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 6; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("===============================================");
Console.WriteLine("The average is ;");
Console.WriteLine(average);
Console.WriteLine("===============================================");
Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
string answer = Console.ReadLine();
switch (answer)
{
case "yes":
Console.WriteLine("===============================================");
Console.WriteLine("please enter the array index you wish to get the value of it");
int index = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("===============================================");
Console.WriteLine("The Value of the selected index is:");
Console.WriteLine(array[index]);
break;
case "no":
Console.WriteLine("===============================================");
Console.WriteLine("HAVE A NICE DAY SIR");
break;
}
}
You can negate a time.Duration
:
then := now.Add(- dur)
You can even compare a time.Duration
against 0
:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
You can see a working example at http://play.golang.org/p/ml7svlL4eW
Just use a simple button
instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script
tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
You can use
sudo apt-get install php7-mysql
or
sudo apt-get install php5-mysql
or
sudo apt-get install php-mysql
This worked for me.
There are two issues are at play here:
The CSS 2.1 specification states that "The :before
and :after
pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers.
Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.
The only thing I can think of that's going to work across browsers is to use javascript to insert the element rather than CSS. I know that's not a great solution, but the :before
and :after
pseudo-selectors just really don't look like they're gonna cut it here.
anyway it's too late but my solution was simple right-click on error-message in Eclipse and choosing Quick Fix >> Ignore for every pom with such errors
A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...
Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.
If you are having trouble changing it to a percentage, then see this answer.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">
<android.support.constraint.Guideline
android:id="@+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@+id/guideline8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
I faced similar issue while doing svn update.
The approach which worked for me is to rename C:\Users\user\AppData\Roaming\TortoiseSVN folder to TortoiseSVN_bkp folder and then tried svn update again. This time I was able to connect to repository and it got updated.
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
h1 is a block level element. You will need to use something like span instead as it is an inline level element (ie: it does not span the whole row).
In your case, I would suggest the following:
style.css
.highlight
{
background-color: green;
}
html
<span class="highlight">only the text will be highlighted</span>
1) Maybe oveflow: hidden; will do the trick?
2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:
button {
position: absolute;
bottom: 0;
}
Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:
tomcat adminport
HTTP/1.1
AJP/1.3
You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).
I had the same problem and here is how it worked for me :
1) Open XAMPP control panel.
2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).
3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.
4) There you find port listen 80 and replace it with 81 in all place and save the file.
5) Now restart Apache and MYSql
6) Now type following in Browser : http://localhost:81/phpmyadmin/
I hope this works.
top, parent, opener (as well as window, self, and iframe) are all window objects.
window.opener
-> returns the window that opens or launches the current popup window.window.top
-> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.window.parent
-> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or selfFor us, the problem was caused by something else. The license file for the DevExpress components included two lines, one for an old version of the components that was not installed on this particular computer. Removing the older version from the license file solved the issue.
The annoying part is that the error message gave no indication to what reference was causing the problems.
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .
spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// Example
if ( is_session_started() === FALSE ) session_start();
If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.
Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/
Then build your own docker image with docker build -t docker-repo:v-x.x.x .
Then use your newly build docker image.
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
This might be because of McAfee using that port.
Doing simple lsof -i 8081
may not show the application and you may have to sudo it.
Do sudo lsof -i 8081
and if this command gives an output you can kill it by using
sudo launchctl remove com.mcafee.agent.macmn
. After this start packager again.
Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date
field can be done in any of the following ways:
Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
For an ascending sort, omit the -
prefix on the string version or use values of 1
, asc
, or ascending
.
As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items
.
It appears that OP's intended approach does work now with a slight change to the quoting of item
.
- set_fact: something="{{ something + [ item ] }}"
with_items:
- one
- two
- three
And a longer example where I've handled the initial case of the list being undefined and added an optional when
because that was also causing me grief:
- set_fact: something="{{ something|default([]) + [ item ] }}"
with_items:
- one
- two
- three
when: item.name in allowed_things.item_list
screen -x
^A
*
, select the one to disconnect, press d
Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)
Note:
PREFIX
is usually^A
=ctrl+a
Note: the display may also be called:
- "user front-end" (in
at
command manual in screen)- "client" (tmux vocabulary where this functionality is
detach-client
)- "terminal" (as we call the window in our user interface) /depending on
1. Reattach a session: screen -x
-x
attach to a not detached screen session without detaching it
2. List displays of this session: PREFIX
*
It is the default key binding for: PREFIX
:displays
.
Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).
term-type size user interface window Perms
---------- ------- ---------- ----------------- ---------- -----
screen 240x60 you@/dev/pts/2 nb 0(zsh) rwx
screen 78x40 you@/dev/pts/0 nb 0(zsh) rwx
Using arrows ?
?
, select the targeted display, press d
If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.
Press ENTER
to quit the listing.
Optionally: in order to make the content fit your screen, reflow: PREFIX
F
(uppercase F)
Excerpt from man page of screen:
displays
Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:
mouseclick
Move to the selected line. Available when "mousetrack" is set to on.space
Refresh the listd
Detach that displayD
Power detach that displayC-g
,enter
, orescape
Exit the list
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
var firstWord = str1[i].split(' ')[0];
alert(firstWord);
}
Solve the issue by following steps.
Uninstalled softwares Vscode and git and reinstalled the same. Changed the git repository clone url from ssh to https.
you can detect offline cross-browser way easily like below
var randomValue = Math.floor((1 + Math.random()) * 0x10000)
$.ajax({
type: "HEAD",
url: "http://yoururl.com?rand=" + randomValue,
contentType: "application/json",
error: function(response) { return response.status == 0; },
success: function() { return true; }
});
you can replace yoururl.com by document.location.pathname
.
The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.
<br>
<%String id = request.getParameter("track_id");%>
<%if (id.length() == 0) {%>
<b><h1>Please Enter Tracking ID</h1></b>
<% } else {%>
<div class="container">
<table border="1" class="table" >
<thead>
<tr class="warning" >
<td ><h4>Track ID</h4></td>
<td><h4>Source</h4></td>
<td><h4>Destination</h4></td>
<td><h4>Current Status</h4></td>
</tr>
</thead>
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from track where track_id="+ id;
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr class="info">
<td><%=resultSet.getString("track_id")%></td>
<td><%=resultSet.getString("source")%></td>
<td><%=resultSet.getString("destination")%></td>
<td><%=resultSet.getString("status")%></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
<%}%>
</body>
Your string is invalid, but assuming it was valid, you'd have to do:
var finalData = str.replace(/\\/g, "");
When you want to replace all the occurences with .replace
, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Cheers
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:
Option Explicit
Dim StdIn: Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Main()
Sub Main()
Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false
Do until objInputFile.AtEndOfStream
tmpStr = objInputFile.ReadLine
If foundStrMatch(tmpStr)=true Then
If foundFirstMatch = false Then
index = getIndex(tmpStr)
foundFirstMatch = true
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
If index = getIndex(tmpStr) Then
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
ElseIf index < getIndex(tmpStr) Then
index = getIndex(tmpStr)
text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
End If
Else
text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub
Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function
Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
getIndex = CInt(char1 & char2)
Else
getIndex = CInt(char1)
End If
End Function
Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
foundStrMatch = true
Else
foundStrMatch = false
End If
End Function
This is the original txt file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
And this is the result I'm expecting
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>
Try the following snippet:
var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this
For Chrome/Chromium
console.log(myObj)
or it's equivalent
console.debug(myObj)
To avoid adding extra div
s when clicking on the link multiple times, and avoid problems when using the script to display forms, you could try a variation of @jek's code.
$('a.ajax').live('click', function() {
var url = this.href;
var dialog = $("#dialog");
if ($("#dialog").length == 0) {
dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
}
// load remote content
dialog.load(
url,
{},
function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser to follow the link
return false;
});`
To people that can't get above fixes working.
Had to change file ssl.py to fix it. Look for function create_default_context and change line:
context = SSLContext(PROTOCOL_SSLv23)
to
context = SSLContext(PROTOCOL_TLSv1)
Maybe someone can create easier solution without editing ssl.py?
import codecs
f=codecs.open("test.html", 'r')
print f.read()
Try something like this.
onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"
Change 1000 to the number of milliseconds you want to delay.
You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.
I find the following function sufficient:
'
' Round Up to the given number of digits
'
Function RoundUp(x As Double, digits As Integer) As Double
If x = Round(x, digits) Then
RoundUp = x
Else
RoundUp = Round(x + 0.5 / (10 ^ digits), digits)
End If
End Function
I know this is old, but I would like to suggest using a linear-gradient to achieve the same effect instead of margin offset. This is will maintain any content at its original place.
HTML
<ul>
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
</ul>
CSS
/* reset */
ul, li, a {
margin: 0; padding: 0;
}
/* nav stuff */
ul, li, a {
display: inline-block;
text-align: center;
}
/* appearance styling */
ul {
/* hacks to make one side slant only */
overflow: hidden;
background: linear-gradient(to right, red, white, white, red);
}
li {
background-color: red;
transform:skewX(-20deg);
-ms-transform:skewX(-20deg);
-webkit-transform:skewX(-20deg);
}
li a {
padding: 3px 6px 3px 6px;
color: #ffffff;
text-decoration: none;
width: 80px;
transform:skewX(20deg);
-ms-transform:skewX(20deg);
-webkit-transform:skewX(20deg);
}
It's been late, but just want to help others if still facing an issue. I found nice JS solution here : https://github.com/google/recaptcha/issues/61#issuecomment-376484690
Here is JavaScript code using jQuery to do so:
$(document).ready(function () {
var width = $('.g-recaptcha').parent().width();
if (width < 302) {
var scale = width / 302;
$('.g-recaptcha').css('transform', 'scale(' + scale + ')');
$('.g-recaptcha').css('-webkit-transform', 'scale(' + scale + ')');
$('.g-recaptcha').css('transform-origin', '0 0');
$('.g-recaptcha').css('-webkit-transform-origin', '0 0');
}
});
IMP Note : It will support All Devices, above and bellow 320px width as well.
Pearson coefficient calculation using pandas in python: I would suggest trying this approach since your data contains lists. It will be easy to interact with your data and manipulate it from the console since you can visualise your data structure and update it as you wish. You can also export the data set and save it and add new data out of the python console for later analysis. This code is simpler and contains less lines of code. I am assuming you need a few quick lines of code to screen your data for further analysis
Example:
data = {'list 1':[2,4,6,8],'list 2':[4,16,36,64]}
import pandas as pd #To Convert your lists to pandas data frames convert your lists into pandas dataframes
df = pd.DataFrame(data, columns = ['list 1','list 2'])
from scipy import stats # For in-built method to get PCC
pearson_coef, p_value = stats.pearsonr(df["list 1"], df["list 2"]) #define the columns to perform calculations on
print("Pearson Correlation Coefficient: ", pearson_coef, "and a P-value of:", p_value) # Results
However, you did not post your data for me to see the size of the data set or the transformations that might be needed before the analysis.
To make mode, controllers with resources, You can type CMD as follows :
php artisan make:model Todo -mcr
or you can check by typing
php artisan help make:model
where you can get all the ideas
Accepted answer in Xcode 11 - Swift 5 - Alamofire 5.0
func postRequest() {
let parameters: [String: Any] = [
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List": [
[
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
],
[
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
]
]
]
AF.request("http://myserver.com", method:.post, parameters: parameters,encoding: JSONEncoding.default) .responseJSON { (response) in
print(response)
}
}
Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):
xhr.open(method, url, true);
You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.
... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.
Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.
I hope that is helpful.
If all the cells are under one column, you could just filter the column and then select "(blank)" and then insert any value into the cells. But be careful, press "alt + 4" to make sure you are inserting value into the visible cells only.
I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.
To match multiple occurrences, one might do something like this:
iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]
This would return a list of the two indices for the original string.
#define CEIL(a, b) (((a) / (b)) + (((a) % (b)) > 0 ? 1 : 0))
Another useful MACROS (MUST HAVE):
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define ABS(a) (((a) < 0) ? -(a) : (a))
Drawing from Van Nguyen's answer above, use update instead of save. This gives you access to the upsert option.
NOTE: This method overrides the entire document when found (From the docs)
var conditions = { name: 'borne' } , update = { $inc: { visits: 1 }} , options = { multi: true };
Model.update(conditions, update, options, callback);
function callback (err, numAffected) { // numAffected is the number of updated documents })
If you want to update a selection of the document, but not the whole thing, you can use the $set method with update. (again, From the docs)... So, if you want to set...
var query = { name: 'borne' }; Model.update(query, ***{ name: 'jason borne' }***, options, callback)
Send it as...
Model.update(query, ***{ $set: { name: 'jason borne' }}***, options, callback)
This helps prevent accidentally overwriting all of your document(s) with { name: 'jason borne' }
.
The fastest way should be:
<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
if (entry.getKey().startsWith("question")) {
String[] values = entry.getValue();
// etc.
Note that you can't do:
for (Map.Entry<String, String[]> entry :
request.getParameterMap().entrySet()) { // WRONG!
for reasons explained here.
select * into newtable from oldtable
You Just need to subtract one day from today's date. In Python datetime.timedelta
object lets you create specific spans of time as a timedelta
object.
datetime.timedelta(1)
gives you the duration of "one day" and is subtractable from a datetime
object. After you subtracted the objects you can use datetime.strftime
in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime
function, you can also directly use strftime
method of datetime
objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
def yesterday(string=False):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime('%Y-%m-%d')
return yesterday
Just have your view controller register for the UIApplicationWillEnterForegroundNotification
notification and react accordingly.
This is a Kotlin way of doing this, I have created button in fragment layout and then set onClickListner in onViewCreated.
according to @Viswanath-Lekshmanan comment
override fun onViewCreated(view: View?, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
btn_FragSP_back.setOnClickListener {
activity?.onBackPressed()
}
}
You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call. So the best way:
$("#mylist li").length
As far as i know there is no built in way of casting strings to booleans,
but if your strings only consist of 'true'
and 'false'
you could shorten your method to the following:
def to_boolean(str)
str == 'true'
end
You could also use alias_attribute
if you still want to be able to refer to them as tasks as well:
class User < ActiveRecord::Base
alias_attribute :jobs, :tasks
has_many :tasks
end
git-bash
reports
fatal: Unable to create <Path to git repo>/.git/index.lock
: File exists.
Deleting index.lock
makes the error go away.
Making use of CSS sprites and data uri gives extra interesting benefits like fast loading and less requests AND we get IE8 support by using image/base64:
HTML
<div class="div1"></div>
<div class="div2"></div>
CSS
.div1:after, .div2:after {
content: '';
display: block;
height: 80px;
width: 80px;
background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20height%3D%2280%22%20width%3D%22160%22%3E%0D%0A%20%20%3Ccircle%20cx%3D%2240%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22red%22%20%2F%3E%0D%0A%20%20%3Ccircle%20cx%3D%22120%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22blue%22%20%2F%3E%0D%0A%3C%2Fsvg%3E);
}
.div2:after {
background-position: -80px 0;
}
For IE8, change to this:
background-image: url(data:image/png;base64,data......);
What is the difference between a strongly typed language and a statically typed language?
A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.
There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.
The opposite of statically typed is "dynamically typed", which means that
For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.
The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.
Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because
Amateurs often conflate them with "static" and "dynamic".
Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.
Professionals can't agree on exactly what the terms mean.
Overall you are unlikely to inform or enlighten your audience.
The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.
By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".
Does one imply the other?
On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:
They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.
They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.
Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.
My best answer for this is to simply use format painter. This might be a bit of a pain, but it works rather well as the problem you are facing is that Gridlines are covered by fill and other effects that are layered on top. Imagine putting a piece of white paper on top of your grid, the grid lines are present underneath, but they just don't show.
So try:
From my experience this is the easiest way to do this quickly. Especially when pasting things in and out of excel.
Again this is not the programmatic way of solving this problem.
simply
the error means that your models has changes and is not in Sync with DB ,so
go to package manager console ,
add-migration foo2
this will give a hint of what is causing the issue ,
may be you removed something or in my case I remove a data annotation .
from there you can get the change and hopefully reverse it in your model.
after that delete foo2 .
You could set timeout before receiving the response and after having received the response set it back to None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)
for file search
find / -xdev -name settings.xml
--> whole computer
find ./ -xdev -name settings.xml
--> current directory & its sub directory
for files with extension type
find . -type f -name "*.iso"
Note: this answer applies only to Angular components and directives, NOT services.
I had this same issue when ngOnInit
(and other lifecycle hooks) were not firing for my components, and most searches led me here.
The issue is that I was using the arrow function syntax (=>
) like this:
class MyComponent implements OnInit {
// Bad: do not use arrow function
public ngOnInit = () => {
console.log("ngOnInit");
}
}
Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:
class MyComponent implements OnInit {
public ngOnInit() {
console.log("ngOnInit");
}
}
You need to prevent the default behaviour. You can either use e.preventDefault()
or return false;
In this case, the best thing is, you can use return false;
here:
<form onsubmit="completeAndRedirect(); return false;">
Using grid?
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: black;
}
body {
display: grid;
grid-template-rows: auto;
justify-items: center;
align-items: center;
}
canvas {
height: 80vh;
width: 80vw;
display: block;
}
_x000D_
<html>
<body>
<canvas></canvas>
</body>
</html>
_x000D_
I'm am very disappointed by the accepted answers in this question. This will not scale. If you read the fine print on cursor.skip( ):
The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return result. As offset (e.g. pageNumber above) increases, cursor.skip() will become slower and more CPU intensive. With larger collections, cursor.skip() may become IO bound.
To achieve pagination in a scaleable way combine a limit( ) along with at least one filter criterion, a createdOn date suits many purposes.
MyModel.find( { createdOn: { $lte: request.createdOnBefore } } )
.limit( 10 )
.sort( '-createdOn' )
Right click on Cell B1
and choose Format Cells. In Custom, put the following in the text box labeled Type:
[h]:mm:ss.000
To set this in code, you can do something like:
Range("A1").NumberFormat = "[h]:mm:ss.000"
That should give you what you're looking for.
NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######
.
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
range()
and xrange()
take a third parameter that specifies a step. So you can do the following.
range(10, 0, -1)
Which gives
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
But for iteration, you should really be using xrange
instead. So,
xrange(10, 0, -1)
Note for Python 3 users: There are no separate
range
andxrange
functions in Python 3, there is justrange
, which follows the design of Python 2'sxrange
.
Yes it is possible in Sony ericssion xylophone w20 .I have got this phone in 2010.but yet this type of phone I have not seen.
You can use VLOOKUP
.
Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:
=VLOOKUP(A2, Sheet2!A:B, 2, 0)
This will return you #N/A
if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.
You can hide the body's scrollbar with overflow: hidden
and set a margin at the same time so that the content doesn't jump:
let marginRightPx = 0;
if(window.getComputedStyle) {
let bodyStyle = window.getComputedStyle(document.body);
if(bodyStyle) {
marginRightPx = parseInt(bodyStyle.marginRight, 10);
}
}
let scrollbarWidthPx = window.innerWidth - document.body.clientWidth;
Object.assign(document.body.style, {
overflow: 'hidden',
marginRight: `${marginRightPx + scrollbarWidthPx}px`
});
And then you can add a disabled scrollbar to the page to fill in the gap:
textarea {_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
width: 11px;_x000D_
outline: none;_x000D_
resize: none;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
border: 0;_x000D_
}
_x000D_
<textarea></textarea>
_x000D_
I did exactly this for my own lightbox implementation. Seems to be working well so far.
You can get the original host from X-Forwarded-For header field.
Also check your URL rewriter. It may throw 404 if something "weird" was found.
import urllib2
f = urllib2.urlopen(target_url)
for l in f.readlines():
print l
I know that is a old question, but...
You can also use this in your class:
@Autowired
private HttpServletRequest context;
And this will provide the current instance of HttpServletRequest
for you use on your method.
As for "Note: we're using maven 2 for our build. I've tried using maven's pre- & post-integration-test phases, but, if a test fails, maven stops and doesn't run post-integration-test, which is no help."
you can try the failsafe-plugin instead, I think it has the facility to ensure cleanup occurs regardless of setup or intermediate stage status
I've successfully used pdftk to remove pages I didn't want/need in pdfs. You can download the program here
You might try something like the following. Taken from here under examples
Remove 'page 13' from in1.pdf to create out1.pdf pdftk in.pdf cat 1-12 14-end output out1.pdf
or:
pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf
In confing.yml
# app/config/config.yml
twig:
globals:
version: '%app.version%'
In Twig view
# twig view
{{ version }}
This is a FAQ:
//someName[3]
means: all someName
elements in the document, that are the third someName
child of their parent -- there may be many such elements.
What you want is exactly the 3rd someName
element:
(//someName)[3]
Explanation: the []
has a higher precedence (priority) than //
. Remember always to put expressions of the type //someName
in brackets when you need to specify the Nth node of their selected node-list.
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
In Martin Fowler's UML Distilled, he states (no pun intended) in Chapter 10 State Machine Diagrams (emphasis mine):
A state diagram can be implemented in three main ways: nested switch, the State pattern, and state tables.
Let's use a simplified example of the states of a mobile phone's display:
Fowler gave an example of C# code, but I've adapted it to my example.
public void HandleEvent(PhoneEvent anEvent) {
switch (CurrentState) {
case PhoneState.ScreenOff:
switch (anEvent) {
case PhoneEvent.PressButton:
if (powerLow) { // guard condition
DisplayLowPowerMessage(); // action
// CurrentState = PhoneState.ScreenOff;
} else {
CurrentState = PhoneState.ScreenOn;
}
break;
case PhoneEvent.PlugPower:
CurrentState = PhoneState.ScreenCharging;
break;
}
break;
case PhoneState.ScreenOn:
switch (anEvent) {
case PhoneEvent.PressButton:
CurrentState = PhoneState.ScreenOff;
break;
case PhoneEvent.PlugPower:
CurrentState = PhoneState.ScreenCharging;
break;
}
break;
case PhoneState.ScreenCharging:
switch (anEvent) {
case PhoneEvent.UnplugPower:
CurrentState = PhoneState.ScreenOff;
break;
}
break;
}
}
Here's an implementation of my example with the GoF State pattern:
Taking inspiration from Fowler, here's a table for my example:
Source State Target State Event Guard Action -------------------------------------------------------------------------------------- ScreenOff ScreenOff pressButton powerLow displayLowPowerMessage ScreenOff ScreenOn pressButton !powerLow ScreenOn ScreenOff pressButton ScreenOff ScreenCharging plugPower ScreenOn ScreenCharging plugPower ScreenCharging ScreenOff unplugPower
Nested switch keeps all the logic in one spot, but the code can be hard to read when there are a lot of states and transitions. It's possibly more secure and easier to validate than the other approaches (no polymorphism or interpreting).
The State pattern implementation potentially spreads the logic over several separate classes, which may make understanding it as a whole a problem. On the other hand, the small classes are easy to understand separately. The design is particularly fragile if you change the behavior by adding or removing transitions, as they're methods in the hierarchy and there could be lots of changes to the code. If you live by the design principle of small interfaces, you'll see this pattern doesn't really do so well. However, if the state machine is stable, then such changes won't be needed.
The state tables approach requires writing some kind of interpreter for the content (this might be easier if you have reflection in the language you're using), which could be a lot of work to do up front. As Fowler points out, if your table is separate from your code, you could modify the behavior of your software without recompiling. This has some security implications, however; the software is behaving based on the contents of an external file.
There is a fluent interface (aka internal Domain Specific Language) approach, too, which is probably facilitated by languages that have first-class functions. The Stateless library exists and that blog shows a simple example with code. A Java implementation (pre Java8) is discussed. I was shown a Python example on GitHub as well.
Intro: There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.
Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to remember.
There is, though, an alternative which is to to try to reinvent the wheel. - Why reinventing the wheel? - Generally because it's a really good way to learn (and sometimes just because the already-existing tool doesn't do exactly what you would like and/or the way you would like it) and the easiest way if you don't know or don't remember the perfect tool for your problem.
So, I propose to reinvent the wheel of the Counter
class from the collections
module (partially at least):
class MyDict(dict):
def __add__(self, oth):
r = self.copy()
try:
for key, val in oth.items():
if key in r:
r[key] += val # You can custom it here
else:
r[key] = val
except AttributeError: # In case oth isn't a dict
return NotImplemented # The convention when a case isn't handled
return r
a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})
print(a+b) # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}
There would probably others way to implement that and there are already tools to do that but it's always nice to visualize how things would basically works.
This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/web/login").permitAll()
.and()
.csrf().ignoringAntMatchers("/contact-email")
.and()
.logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles(ADMIN.toString())
.and()
.withUser("guest").password("guest").roles(GUEST.toString());
}
}
I have included full configuration but the key line is:
.csrf().ignoringAntMatchers("/contact-email")
I might be a bit late to answer this but this will be useful for new people looking for this answer.
The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.
I got into this issue not long ago and I found the solution using media queries.
Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS
I will add the code here as well:
HTML:
<div class="videoBgWrapper">
<video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
<source src="videosfolder/video.webm" type="video/webm">
<source src="videosfolder/video.mp4" type="video/mp4">
<source src="videosfolder/video.ogv" type="video/ogg">
</video>
</div>
CSS:
.videoBgWrapper {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.videoBg{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.videoBg{
width: 100%;
height: auto;
}
}
@media (max-aspect-ratio: 16/9) {
.videoBg {
width: auto;
height: 100%;
}
}
I hope you find it useful.
I spent a lot of time reading the various answers on this thread, and for me, it was actually something slightly different (related, but different). On Mobile Safari (iOS devices), if the login form is HIDDEN when the page loads, the prompt will not appear (after you show the form then submit it). You can test with the following code, which displays the form 5 seconds after the page load. Remove the JS and the display: none and it works. I am yet to find a solution to this, just posted in case anyone else has the same issue and can not figure out the cause.
JS:
$(function() {
setTimeout(function() {
$('form').fadeIn();
}, 5000);
});
HTML:
<form method="POST" style="display: none;">
<input name='email' id='email' type='email' placeholder='email' />
<input name='password' id='password' type='password' placeholder='password' />
<button type="submit">LOGIN</button>
</form>
Here is an overview in a table format in order to show the differences between Pool.apply
, Pool.apply_async
, Pool.map
and Pool.map_async
. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:
| Multi-args Concurrence Blocking Ordered-results
---------------------------------------------------------------------
Pool.map | no yes yes yes
Pool.map_async | no yes no yes
Pool.apply | yes no yes no
Pool.apply_async | yes yes no no
Pool.starmap | yes yes yes yes
Pool.starmap_async| yes yes no no
Pool.imap
and Pool.imap_async
– lazier version of map and map_async.
Pool.starmap
method, very much similar to map method besides it acceptance of multiple arguments.
Async
methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.
Pool.map
(or Pool.apply
)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.
Is called for a list of jobs in one time
results = pool.map(func, [1, 2, 3])
Can only be called for one job
for x, y in [[1, 1], [2, 2]]:
results.append(pool.apply(func, (x, y)))
def collect_result(result):
results.append(result)
Is called for a list of jobs in one time
pool.map_async(func, jobs, callback=collect_result)
Can only be called for one job and executes a job in the background in parallel
for x, y in [[1, 1], [2, 2]]:
pool.apply_async(worker, (x, y), callback=collect_result)
Is a variant of pool.map
which support multiple arguments
pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.
pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)
Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html
In addition to disabling the options that should not be selectable i wanted to actually make them dissapear from the list, but still be able to enable them should i need to later:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
This finds all select elements with a readonly attribute, then finds all options inside those selects that are not selected, then it hides them and disables them.
It is important to separate the jquery query in 2 for performance reasons, because jquery reads them from right to left, the code:
$("select[readonly] option:not(:selected)")
will first find all unselected options in the document and then filter those that are inside selects with a readonly attribute.
You can handle WM_NCPAINT
message of TextBox
and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
[DllImport("user32")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
private const int WM_NCPAINT = 0x85;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCPAINT && this.Focused)
{
var dc = GetWindowDC(Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);
}
}
}
}
Result
The painting of borders while the control is focused is completely flicker-free:
BorderColor property for TextBox
In the current post I just change the border color on focus. You can also add a BorderColor
property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox
which has BorderColor
property:
in the following post:
My solution:
var pressedKeys = {};
window.onkeyup = function(e) { pressedKeys[e.keyCode] = false; }
window.onkeydown = function(e) { pressedKeys[e.keyCode] = true; }
I can now check if any key is pressed anywhere else in the script by checking
pressedKeys["code of the key"]
If it's true, the key is pressed.
You can use pygame's surfarray module. This module has a 3d pixel array returning method called pixels3d(surface). I've shown usage below:
from pygame import surfarray, image, display
import pygame
import numpy #important to import
pygame.init()
image = image.load("myimagefile.jpg") #surface to render
resolution = (image.get_width(),image.get_height())
screen = display.set_mode(resolution) #create space for display
screen.blit(image, (0,0)) #superpose image on screen
display.flip()
surfarray.use_arraytype("numpy") #important!
screenpix = surfarray.pixels3d(image) #pixels in 3d array:
#[x][y][rgb]
for y in range(resolution[1]):
for x in range(resolution[0]):
for color in range(3):
screenpix[x][y][color] += 128
#reverting colors
screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen
display.flip() #update display
while 1:
print finished
I hope been helpful. Last word: screen is locked for lifetime of screenpix.
import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file
You can improve this code with del dirs[:]
which will be like following .
import os
for subdir, dirs, files in os.walk('./'):
del dirs[:]
for file in files:
do some stuff
print file
Or even better if you could point os.walk with current working directory .
import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
del dirs[:] # remove the sub directories.
for file in files:
do some stuff
print file
Pass a keyword argument name with value as your view name e.g home
or home-view
etc. to url()
function.
url(r'^home$', 'common.views.view1', 'home'),
url(r'^home$', 'common.views.view1', name='home'),
function check(selId) {
var sel = document.getElementById(selId);
var dropDown_sel = sel.options[sel.selectedIndex].text;
if (dropDown_sel != "none") {
state=1;
//state is a Global variable initially it is set to 0
}
}
function checkstatevalue() {
if (state==1) {
return 1;
}
return false;
}
and html is for example
<form name="droptest" onSubmit="return checkstatevalue()">
<select id='Sel1' onchange='check("Sel1");'>
<option value='junaid'>Junaid</option>
<option value='none'>none</option>
<option value='ali'>Ali</option>
</select>
</form>
Now when submitting a form first check what is the value of state if it is 0 it means that no item has been selected.
This should work:
System.currentTimeMillis();
Using generics (as in the above answers) is your best bet here. I've just double checked and:
test.put("test", arraylistone);
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");
will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.
If you are still seeking for the best solution in 2018, I found the way this works perfectly if you have at least one free pseudo element( ::after or ::before ).
You just have to add class to your row like this: <div class="row
vertical-divider ">
And add this to your CSS:
.row.vertical-divider [class*='col-']:not(:last-child)::after {
background: #e0e0e0;
width: 1px;
content: "";
display:block;
position: absolute;
top:0;
bottom: 0;
right: 0;
min-height: 70px;
}
Any row with this class will now have vertical divider between all of the columns it contains...
You can see how this works in this example.
You can simply pass more arguments to summarise
:
df %>% group_by(grp) %>% summarise(mean(a), mean(b), mean(c), mean(d))
Source: local data frame [3 x 5]
grp mean(a) mean(b) mean(c) mean(d)
1 1 2.500000 3.500000 2.000000 3.0
2 2 3.800000 3.200000 3.200000 2.8
3 3 3.666667 3.333333 2.333333 3.0
I had this error trying to connect with a different user than root
I'd set up to limit access.
In mysql I'd set up user MofX
with host %
and it wouldn't connect.
When I changed the user's host to 127.0.0.1
, as in 'MofX'@'127.0.0.1', it worked.
The .git folder is only stored in the root directory of the repo, not all the sub-directories like subversion. You should be able to just delete that one folder, unless you are using Submodules...then they will have one too.
To answer the original question on how to get the index as an integer for the desired selection, the following will work :
df[df['A']==5].index.item()
I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.
Sample document
{
"swagger": "2.0",
"info": {
"title": "Company Admin Panel",
"description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
"contact": {
"email": "[email protected]"
},
"version": "1.0.0"
},
"host": "localhost/cv_admin/api",
"schemes": [
"http"
],
"paths": {
"/getCustomerByEmail.php": {
"post": {
"summary": "List the details of customer by the email.",
"consumes": [
"string",
"application/json",
"application/x-www-form-urlencoded"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "email",
"in": "body",
"description": "Customer email to ge the data",
"required": true,
"schema": {
"properties": {
"id": {
"properties": {
"abc": {
"properties": {
"inner_abc": {
"type": "number",
"default": 1,
"example": 123
}
},
"type": "object"
},
"xyz": {
"type": "string",
"default": "xyz default value",
"example": "xyz example value"
}
},
"type": "object"
}
}
}
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "Email required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getCustomerById.php": {
"get": {
"summary": "List the details of customer by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Customer ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "ID required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getShipmentById.php": {
"get": {
"summary": "List the details of shipment by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Shipment ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the shipment"
},
"404": {
"description": "Shipment does not exist"
},
"400": {
"description": "ID required"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
}
},
"definitions": {
}
}
This can be imported into Postman as follow.
You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.
This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.
<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;
Here is a great way to build dynamic fields for a pivot query:
--summarize values to a tmp table
declare @STR varchar(1000)
SELECT @STr = COALESCE(@STr +', ', '')
+ QUOTENAME(DateRange)
from (select distinct DateRange, ID from ##pivot)d order by ID
---see the fields generated
print @STr
exec(' .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')
You have Integer#to_s(base)
and String#to_i(base)
available to you.
Integer#to_s(base)
converts a decimal number to a string representing the number in the base specified:
9.to_s(2) #=> "1001"
while the reverse is obtained with String#to_i(base)
:
"1001".to_i(2) #=> 9
let phone = "tel://\("1234567890")";
let url:NSURL = NSURL(string:phone)!;
UIApplication.sharedApplication().openURL(url);
Try to see if the following code helps you:
Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)
Why not use commands.getoutput() instead?
import commands
text = "Mario Balotelli"
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)
Interestingly putting <httpCookies httpOnlyCookies="false"/>
doesn't seem to disable httpOnlyCookies
in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.
Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on forums.asp.net
Some fallback logic can be added to handle the presence of a Load Balancer.
Also, through inspection, the X-Forwarded-For
header happens to be set anyway even without a Load Balancer (possibly because of additional Kestrel layer?):
public string GetRequestIP(bool tryUseXForwardHeader = true)
{
string ip = null;
// todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For
// X-Forwarded-For (csv list): Using the First entry in the list seems to work
// for 99% of cases however it has been suggested that a better (although tedious)
// approach might be to read each IP from right to left and use the first public IP.
// http://stackoverflow.com/a/43554000/538763
//
if (tryUseXForwardHeader)
ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();
// RemoteIpAddress is always null in DNX RC1 Update1 (bug).
if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
if (ip.IsNullOrWhitespace())
ip = GetHeaderValueAs<string>("REMOTE_ADDR");
// _httpContextAccessor.HttpContext?.Request?.Host this is the local host.
if (ip.IsNullOrWhitespace())
throw new Exception("Unable to determine caller's IP.");
return ip;
}
public T GetHeaderValueAs<T>(string headerName)
{
StringValues values;
if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
{
string rawValues = values.ToString(); // writes out as Csv when there are multiple.
if (!rawValues.IsNullOrWhitespace())
return (T)Convert.ChangeType(values.ToString(), typeof(T));
}
return default(T);
}
public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
if (string.IsNullOrWhiteSpace(csvList))
return nullOrWhitespaceInputReturnsNull ? null : new List<string>();
return csvList
.TrimEnd(',')
.Split(',')
.AsEnumerable<string>()
.Select(s => s.Trim())
.ToList();
}
public static bool IsNullOrWhitespace(this string s)
{
return String.IsNullOrWhiteSpace(s);
}
Assumes _httpContextAccessor
was provided through DI.
I was looking for a way to prevent all body scrolling when there's a popup with a scrollable area (a "shopping cart" popdown that has a scrollable view of your cart).
I wrote a far more elegant solution using minimal javascript to just toggle the class "noscroll" on your body when you have a popup or div that you'd like to scroll (and not "overscroll" the whole page body).
while desktop browsers observe overflow:hidden -- iOS seems to ignore that unless you set the position to fixed... which causes the whole page to be a strange width, so you have to set the position and width manually as well. use this css:
.noscroll {
overflow: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
and this jquery:
/* fade in/out cart popup, add/remove .noscroll from body */
$('a.cart').click(function() {
$('nav > ul.cart').fadeToggle(100, 'linear');
if ($('nav > ul.cart').is(":visible")) {
$('body').toggleClass('noscroll');
} else {
$('body').removeClass('noscroll');
}
});
/* close all popup menus when you click the page... */
$('body').click(function () {
$('nav > ul').fadeOut(100, 'linear');
$('body').removeClass('noscroll');
});
/* ... but prevent clicks in the popup from closing the popup */
$('nav > ul').click(function(event){
event.stopPropagation();
});
Simply
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
class Simple{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
It will give the following output:
main() method invoked
10
I came up with this bash script. It always keep the branches develop
, qa
, master
.
git-clear() {
git pull -a > /dev/null
local branches=$(git branch --merged | grep -v 'develop' | grep -v 'master' | grep -v 'qa' | sed 's/^\s*//')
branches=(${branches//;/ })
if [ -z $branches ]; then
echo 'No branches to delete...'
return;
fi
echo $branches
echo 'Do you want to delete these merged branches? (y/n)'
read yn
case $yn in
[^Yy]* ) return;;
esac
echo 'Deleting...'
git remote prune origin
echo $branches | xargs git branch -d
git branch -vv
}
I encountered similar problems too. In my case it was solved by getting the cursor in this way:
cursor = self.conn.cursor(buffered=True)
One option is to use altertify, this gives a nice looking alert box.
Simply include the required libraries from here, and use the following piece of code to display the alert box.
alertify.confirm("This is a confirm dialog.",
function(){
alertify.success('Ok');
},
function(){
alertify.error('Cancel');
});
The output will look like this. To see it in action here is the demo
I'd use the -
variant for std::vector
only - it's pretty clear what is meant, and the simplicity of the operation (which isn't more than a pointer subtraction) is expressed by the syntax (distance
, on the other side, sounds like pythagoras on the first reading, doesn't it?). As UncleBen points out, -
also acts as a static assertion in case vector
is accidentially changed to list
.
Also I think it is much more common - have no numbers to prove it, though. Master argument: it - vec.begin()
is shorter in source code - less typing work, less space consumed. As it's clear that the right answer to your question boils down to be a matter of taste, this can also be a valid argument.
You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.
I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.
$('#yesCheck').click(function() {
$('#ifYes').slideDown();
});
$('#noCheck').click(function() {
$('#ifYes').slideUp();
});
It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//it work fine with any spaces *don't forget space in sting b
Change
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)
to
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
I made my function:
function summery($text, $limit) {
$words=preg_split('/\s+/', $text);
$count=count(preg_split('/\s+/', $text));
if ($count > $limit) {
$text=NULL;
for($i=0;$i<$limit;$i++)
$text.=$words[$i].' ';
$text.='...';
}
return $text;
}
In case you want to use the Docker image as a "regular" Ubuntu installation, you can also run unminimize
. This will install a lot more than ifconfig
, so this might not be what you want.
knockoutJs Inbuild library validation functions
By extending it the field get validated
1) number
self.number = ko.observable(numberValue)
.extend({ number: true});
TestCase
numberValue = '0.0' --> true
numberValue = '0' --> true
numberValue = '25' --> true
numberValue = '-1' --> true
numberValue = '-3.5' --> true
numberValue = '11.112' --> true
numberValue = '0x89f' --> false
numberValue = '' --> false
numberValue = 'sfsd' --> false
numberValue = 'dg##$' --> false
2) digit
self.number = ko.observable(numberValue)
.extend({ digit: true});
TestCase
numberValue = '0' --> true
numberValue = '25' --> true
numberValue = '0.0' --> false
numberValue = '-1' --> false
numberValue = '-3.5' --> false
numberValue = '11.112' --> false
numberValue = '0x89f' --> false
numberValue = '' --> false
numberValue = 'sfsd' --> false
numberValue = 'dg##$' --> false
3) min and max
self.number = ko.observable(numberValue)
.extend({ min: 5}).extend({ max: 10});
This field accept value between 5 and 10 only
TestCase
numberValue = '5' --> true
numberValue = '6' --> true
numberValue = '6.5' --> true
numberValue = '9' --> true
numberValue = '11' --> false
numberValue = '0' --> false
numberValue = '' --> false
Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?
Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.
Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.
I think what you want is to swap out at runtime a version of your config file, if so create a copy of your config file (also give it the relevant extension like .Debug or .Release) that has the correct addresses (which gives you a debug version and a runtime version ) and create a postbuild step that copies the correct file depending on the build type.
Here is an example of a postbuild event that I've used in the past which overrides the output file with the correct version (debug/runtime)
copy "$(ProjectDir)ServiceReferences.ClientConfig.$(ConfigurationName)" "$(ProjectDir)ServiceReferences.ClientConfig" /Y
where : $(ProjectDir) is the project directory where the config files are located $(ConfigurationName) is the active configuration build type
EDIT: Please see Marc's answer for a detailed explanation on how to do this programmatically.
I know this is the old one. But this may help others.
I have added SP calling function between BEGIN/END. Here is a working script.
ALTER Proc [dbo].[DepartmentAddOrEdit]
@Id int,
@Code varchar(100),
@Name varchar(100),
@IsActive bit ,
@LocationId int,
@CreatedBy int,
@UpdatedBy int
AS
IF(@Id = 0)
BEGIN
INSERT INTO Department (Code,Name,IsActive,LocationId,CreatedBy,UpdatedBy,CreatedAt)
VALUES(@Code,@Name,@IsActive,@LocationId,@CreatedBy,@UpdatedBy,CURRENT_TIMESTAMP)
EXEC dbo.LogAdd @CreatedBy,'DEPARTMENT',@Name
END
ELSE
UPDATE Department SET
Code = @Code,
Name = @Name,
IsActive = @IsActive,
LocationId = @LocationId,
CreatedBy = @CreatedBy,
UpdatedBy = @UpdatedBy,
UpdatedAt = CURRENT_TIMESTAMP
where Id = @Id
What the OP wants to do, is delete additional properties in his Google analytics. Properties that are not his but belong to someone else.
Apparently, the only way to do this, is to contact the owner of that website who is the administrator, and asked them to remove you.
Or you can just create a new Google account, and add your properties to the new account.
None of these are real good solutions. Thank you Google for caring so much about SEO people.
To add insult to injury, if you go over 25 accounts, you must contact Google to get permission to add another.
Lesson learned: Do not add other peoples websites to your Google analytics account. Create a separate account so that if you have to start over, you don't lose any data from your websites. It's also good to have more than one Google analytics account.
You could decorate your view model property with the [DisplayName]
attribute and specify the text to be used:
[DisplayName("foo bar")]
public string SomekingStatus { get; set; }
Or use another overload of the LabelFor helper which allows you to specify the text:
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
And, no, you cannot specify a class name in MVC3 as you tried to do, as the LabelFor
helper doesn't support that. However, this would work in MVC4 or 5.
Put the tab name on the page header or group TableRow1 in your report so that it will appear in the "A1" position on each Excel sheet. Then run this macro in your Excel workbook.
Sub SelectSheet()
For i = 1 To ThisWorkbook.Sheets.Count
mysheet = "Sheet" & i
On Error GoTo 10
Sheets(mysheet).Select
Set Target = Range("A1")
If Target = "" Then Exit Sub
On Error GoTo Badname
ActiveSheet.Name = Left(Target, 31)
GoTo 10
Badname:
MsgBox "Please revise the entry in A1." & Chr(13) _
& "It appears to contain one or more " & Chr(13) _
& "illegal characters." & Chr(13)
Range("A1").Activate
10
Next i
End Sub
fwrite($handle, "<br>"."\r\n");
Add this under
$password = $_POST['password'].PHP_EOL;
this. .
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
<c:if test="#{not empty user or user.userId eq 0}">
<a href="Images/thumb_02.jpg" target="_blank" ></a>
<img src="Images/thumb_02.jpg" />
</c:if>
<c:if test="#{empty user or user.userId eq 0}">
<a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
<img src="/DisplayBlobExample?userId=#{user.userId}" />
</c:if>
</html>
Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:
<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
Please note that the proposed code is only valid with Python 2
Here is an example:
from Tkinter import * # from x import * is bad practice
from ttk import *
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
class VerticalScrolledFrame(Frame):
"""A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling
"""
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class SampleApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="Shrink the window to activate the scrollbar.")
self.label.pack()
buttons = []
for i in range(10):
buttons.append(Button(self.frame.interior, text="Button " + str(i)))
buttons[-1].pack()
app = SampleApp()
app.mainloop()
It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.
edit:
to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.
to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).
to 3)
Well, it positions the window on the canvas.
One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.
another alternative is to use a form replacement script/library. They usually hide the original element and replace them with a div or span, which you can style in whatever way you like.
Examples are:
http://customformelements.net (based on mootools) http://www.htmldrive.net/items/show/481/jQuery-UI-Radiobutton-und-Checkbox-Replacement.html
=$G1="X"
would be the correct (and easiest) method. Just select the entire sheet first, as conditional formatting only works on selected cells. I just tried it and it works perfectly. You must start at G1 rather than G2 otherwise it will offset the conditional formatting by a row.
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
you should declare label first use this :
Select Case parameter
Case "userID"
' does something here.
Case "packageID"
' does something here.
Case "mvrType"
If otherFactor Then
' does something here.
Else
GoTo else
End If
Case Else
else :
' does some processing...
Exit Select
End Select
Edit: As suggested in comments. This solution is for Linux OS. That too if you have installed ruby manually from package-manager.
If you want to have multiple ruby versions, better to have RVM. In that case you don't need to remove ruby older version.
Still if want to remove then follow the steps below:
First you should find where Ruby is:
whereis ruby
will list all the places where it exists on your system, then you can remove all them explicitly. Or you can use something like this:
rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem
Cygwin mount
now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab
, then restart your shell:
c:/Users /home none bind 0 0
One more (in the future) way to conditionally apply style is by conditionally creating scoped style
<style scoped type="text/css" ng-if="...">
</style>
But nowadays only FireFox supports scoped styles.
There's no such thing as an empty char. The closest you can get is '\0'
, the Unicode "null" character. Given that you can embed that within string literals or express it on its own very easily, why would you want a separate field for it? Equally, the "it's easy to confuse ""
and " "
" arguments don't apply for '\0'
.
If you could give an example of where you'd want to use it and why you think it would be better, that might help...
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
Firstly, BEGIN..END
are merely syntactic elements, and have nothing to do with transactions.
Secondly, in Oracle all individual DML statements are atomic (i.e. they either succeed in full, or rollback any intermediate changes on the first failure) (unless you use the EXCEPTIONS INTO option, which I won't go into here).
If you wish a group of statements to be treated as a single atomic transaction, you'd do something like this:
BEGIN
SAVEPOINT start_tran;
INSERT INTO .... ; -- first DML
UPDATE .... ; -- second DML
BEGIN ... END; -- some other work
UPDATE .... ; -- final DML
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO start_tran;
RAISE;
END;
That way, any exception will cause the statements in this block to be rolled back, but any statements that were run prior to this block will not be rolled back.
Note that I don't include a COMMIT - usually I prefer the calling process to issue the commit.
It is true that a BEGIN..END block with no exception handler will automatically handle this for you:
BEGIN
INSERT INTO .... ; -- first DML
UPDATE .... ; -- second DML
BEGIN ... END; -- some other work
UPDATE .... ; -- final DML
END;
If an exception is raised, all the inserts and updates will be rolled back; but as soon as you want to add an exception handler, it won't rollback. So I prefer the explicit method using savepoints.
You can use selenium and the webdriver for Firefox.
import selenium.webdriver
import selenium.common
options = selenium.webdriver.firefox.options.Options()
# options.headless = True
with selenium.webdriver.Firefox(options=options) as driver:
driver.get('http://google.com')
time.sleep(2)
root=driver.find_element_by_tag_name('html')
root.screenshot('whole page screenshot.png')
my quick answer with basic java arithmetic calculation is this:
First consider the following values:
1 Minute = 60 Seconds
1 Hour = 3600 Seconds ( 60 * 60 )
1 Day = 86400 Second ( 24 * 3600 )
the code snippet is as follows:
int input=500000;
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = input / 86400;
numberOfHours = (input % 86400 ) / 3600 ;
numberOfMinutes = ((input % 86400 ) % 3600 ) / 60
numberOfSeconds = ((input % 86400 ) % 3600 ) % 60 ;
I hope to be helpful to you.
You mean JavaScript? Just output it like anything else in the page:
<script type="text/javascript">
<?php echo "alert('message');"; ?>
</script>
If want PHP to generate a custom message for the alert dialog, then basically you want to write your JavaScript as usual in the HTML, but insert PHP echo statements in the middle of your JavaScript where you want the messages, like:
<script type="text/javascript">
alert('<?php echo $custom_message; ?>');
</script>
Or you could even do something like this:
<script type="text/javascript">
var alertMsg = '<?php echo $custom_message; ?>';
alert(alertMsg);
</script>
Basically, think about where in your JavaScript you want PHP to generate dynamic output and just put an echo statement there.
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
For completeness, the boost way would be to use boost::format
cout << boost::format("%s %s > %s") % a % b % c;
Take your pick. The boost solution has the advantage of type safety with the sprintf
format (for those who find the <<
syntax a bit clunky).
You can make this bit more cleaner by using:
$http.get(url)
.then(function (response) {
console.log('get',response)
})
.catch(function (data) {
// Handle error here
});
Similar to @this.lau_ answer, different approach.
import java.util.Scanner;
public class LargestSmallestNum {
public void findLargestSmallestNo() {
int smallest = Integer.MAX_VALUE;
int large = 0;
int num;
System.out.println("enter the number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
num = input.nextInt();
if (num > large)
large = num;
if (num < smallest)
smallest = num;
System.out.println("the largest is:" + large);
System.out.println("Smallest no is : " + smallest);
}
}
public static void main(String...strings){
LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
largestSmallestNum.findLargestSmalestNo();
}
}
It could be the self-closing tag of link at the end, try:
<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/>
and in your main.css file try:
body,div {
font-family: 'Bungee Inline', cursive;
}
Use a SQL DATA READER:
In this example i use a List instead an array.
try
{
SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
connection.Open();
SqlDataReader reader = comm.ExecuteReader();
List<string> str = new List<string>();
int i=0;
while (reader.Read())
{
str.Add( reader.GetValue(i).ToString() );
i++;
}
reader.Close();
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
Import the file into Excel by first opening excel, then going to DATA, import from TXT File, choose the csv extension which will preserve 0 prefixed values, and save that column as TEXT because excel will drop the leading 0 otherwise (DO NOT double click to open with Excel if you have numeric data in a field starting with a 0 [zero]). Then just save out as a Tab Delimited Text file. When you are importing into excel you get an option to save as GENERAL, TEXT, etc.. choose TEXT so that quotes in the middle of a string in a field like YourCompany,LLC are preserved also...
BULK INSERT dbo.YourTableName
FROM 'C:\Users\Steve\Downloads\yourfiletoIMPORT.txt'
WITH (
FirstRow = 2, (if skipping a header row)
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
I wish I could use the FORMAT and Fieldquote functionality but that does not appear to be supported in my version of SSMS
I've fixed this…by simply opening a new tab.
Why it wasn't working I'm not entirely sure, but it could have something to do with how Chrome deals with multiple downloads on a page, perhaps it thought they were spam and just ignored them.
I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.
#!/bin/bash
PROPERTY_FILE=filename.properties
function getProperty {
PROP_KEY=$1
PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
echo $PROP_VALUE
}
echo "# Reading property from $PROPERTY_FILE"
DB_USER=$(getProperty "db.username")
DB_PASS=$(getProperty "db.password")
ROOT_LOC=$(getProperty "root.location")
echo $DB_USER
echo $DB_PASS
echo $ROOT_LOC
echo "Writing on DB ... "
mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL
update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
EOFMYSQL
echo "Writing root location($ROOT_LOC) is done ... "
counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;
if [ "$counter" = "1" ]
then
echo "ROOT location updated"
fi
Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.
You can perform tasks for a limited time after your application is directed to go to the background, but only for the duration provided. Running for longer than this will cause your application to be terminated. See the "Completing a Long-Running Task in the Background" section of the iOS Application Programming Guide for how to go about this.
Others have piggybacked on playing audio in the background as a means of staying alive as a background process, but Apple will only accept such an application if the audio playback is a legitimate function. Item 2.16 on Apple's published review guidelines states:
Multitasking apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion, local notifications, etc
None of the suggestions here helped me with my situation, but I read something that did give me an answer. I have a ViewController with a fixed set of UI controls followed by a UIWebView. I wanted the entire page to scroll as though the UI controls were connected to the HTML content, so I disable scrolling on the UIWebView and must then set the content size of a parent scroll view correctly.
The important tip turned out to be that UIWebView does not report its size correctly until rendered to the screen. So when I load the content I set the content size to the available screen height. Then, in viewDidAppear I update the scrollview's content size to the correct value. This worked for me because I am calling loadHTMLString on local content. If you are using loadRequest you may need to update the contentSize in webViewDidFinishLoad also, depending on how quickly the html is retrieved.
There is no flickering, because only the invisible part of the scroll view is changed.
Just call ID:
public void delNoti(int id) {((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(id);}
As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.7 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/bin/python3.7 2 manual mode
Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*
I don't think it's recommended to update the local.properties
file to get to add the missing environment vars.
sdk can be installed on /Library/Android/sdk or /usr/local/ to be sure check it by
which sdkmanager
export ANDROID_HOME=$HOME/Library/Android/sdk
or
export ANDROID_HOME="/usr/local/share/android-sdk"
Then add it to the $PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/build-tools/28.0.1:$PATH
export ANT_HOME=/usr/local/opt/ant
export MAVEN_HOME=/usr/local/opt/maven
export GRADLE_HOME=/usr/local/opt/gradle
export ANDROID_HOME=/usr/local/share/android-sdk
export ANDROID_SDK_ROOT=/usr/local/share/android-sdk
export ANDROID_NDK_HOME=/usr/local/share/android-ndk
export INTEL_HAXM_HOME=/usr/local/Caskroom/intel-haxm
I used brew cask
to install Android SDK following these instructions.
More info see https://developer.android.com/studio/intro/update#sdk-manager
This code:
"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());
Returns - to me - true
if offline, and false
, otherwise. (well, I don't know if this true to all computers).
This works much faster than the other approaches, up here.
EDIT: I found this only working, if the "flip switch" (on a laptop), or some other system-defined option, for the internet connection, is off. That's, the system itself knows not to look for any IP addresses.
With Chris's inspiring post here:
https://css-tricks.com/different-transitions-for-hover-on-hover-off/
I managed to come up with this:
#banner
{
display:block;
width:100%;
background-repeat:no-repeat;
background-position:center bottom;
background-image:url(../images/image1.jpg);
/* HOVER OFF */
@include transition(background-image 0.5s ease-in-out);
&:hover
{
background-image:url(../images/image2.jpg);
/* HOVER ON */
@include transition(background-image 0.5s ease-in-out);
}
}
If you don't need the DATETIME value in the rest of your code, it'd be more efficient, simple and secure to use an UPDATE query with a sub-select, something like
UPDATE products SET t=(SELECT f FROM products WHERE id=17) WHERE id=42;
or in case it's in the same row in a single table, just
UPDATE products SET t=f WHERE id=42;