The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
In Python 3.6+:
import datetime
timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
2020-01-15 19:51:41
type(value)
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
simply use replace
like this:
(datetime.date.now()).strftime("%Y/%m/%d").replace("/0", "/")
it will output:
'2017/7/21'
You can set date as environment variable and later u can use it
setenv DATE `date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
or
DATE =`date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
If you want an integer, try this code:
import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])
Output:
1545474382803
You can try this it'll convert the date format to DD-MM-YYYY:
df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)
This works in Python 2 and 3:
>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998
Just following the official docs... https://docs.python.org/2/library/time.html#module-time
According to Wikipedia:
[...] A traditional pipe is "unnamed" because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be "unlinked" or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).
Create a class that implements the Runnable
interface. Put the code you want to run in the run()
method - that's the method that you must write to comply to the Runnable
interface. In your "main" thread, create a new Thread
class, passing the constructor an instance of your Runnable
, then call start()
on it. start
tells the JVM to do the magic to create a new thread, and then call your run
method in that new thread.
public class MyRunnable implements Runnable {
private int var;
public MyRunnable(int var) {
this.var = var;
}
public void run() {
// code in the other thread, can reference "var" variable
}
}
public class MainThreadClass {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable(10);
Thread t = new Thread(myRunnable)
t.start();
}
}
Take a look at Java's concurrency tutorial to get started.
If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future
, Callable
, Executor
classes in the java.util.concurrent
package.
If you need only key comparison:
_.reduce(a, function(result, value, key) {
return b[key] === undefined ? key : []
}, []);
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.
Syntax For The SQL WITH Clause
The following is the syntax of the SQL WITH clause when using a single sub-query alias.
WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]
When using multiple sub-query aliases, the syntax is as follows.
WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]
In the syntax documentation above, the occurrences of alias_name
is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.
For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx
Sometimes it may be required to execute the update atomically that is using one update request to the database without reading it first.
Also get
-set attribute
-save
may cause problems if such updates may be done concurrently or if you need to set the new value based on the old field value.
In such cases query expressions together with update
may by useful:
TemperatureData.objects.filter(id=1).update(value=F('value') + 1)
You can use a quick lambda
function to check if all the values in a given row are 0
. Then you can use the result of applying that lambda
as a way to choose only the rows that match or don't match that condition:
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3),
index=['one', 'two', 'three', 'four', 'five'],
columns=list('abc'))
df.loc[['one', 'three']] = 0
print df
print df.loc[~df.apply(lambda row: (row==0).all(), axis=1)]
Yields:
a b c
one 0.000000 0.000000 0.000000
two 2.240893 1.867558 -0.977278
three 0.000000 0.000000 0.000000
four 0.410599 0.144044 1.454274
five 0.761038 0.121675 0.443863
[5 rows x 3 columns]
a b c
two 2.240893 1.867558 -0.977278
four 0.410599 0.144044 1.454274
five 0.761038 0.121675 0.443863
[3 rows x 3 columns]
You can change the highlight color in several ways.
Change the selectionStyle property of your cell. If you change it to UITableViewCellSelectionStyleGray
, it will be gray.
Change the selectedBackgroundView
property. Actually what creates the blue gradient is a view. You can create a view and draw what ever you like, and use the view as the background of your table view cells.
You could use a recursive scalar function:-
set nocount on
create table location (
id int,
name varchar(50),
parent int
)
insert into location values
(1,'france',null),
(2,'paris',1),
(3,'belleville',2),
(4,'lyon',1),
(5,'vaise',4),
(6,'united kingdom',null),
(7,'england',6),
(8,'manchester',7),
(9,'fallowfield',8),
(10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
declare @returnValue varchar(1024)=''
declare @parent int
select @returnValue+=' > '+name,@parent=parent
from location
where id=@child
if @parent is not null
set @returnValue=dbo.breadcrumb(@parent)+@returnValue
return @returnValue
end
go
declare @location int=1
while @location<=10 begin
print dbo.breadcrumb(@location)+' >'
set @location+=1
end
produces:-
> france >
> france > paris >
> france > paris > belleville >
> france > lyon >
> france > lyon > vaise >
> united kingdom >
> united kingdom > england >
> united kingdom > england > manchester >
> united kingdom > england > manchester > fallowfield >
> united kingdom > england > manchester > withington >
Assuming you're using a std::ofstream
to write to file, the following snippet will write a std::string
to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
Try checking if the page has been scrolled and only then reset position:
var scrolled = false;
$(window).scroll(function(){
scrolled = true;
});
if ( window.location.hash && scrolled ) {
$(window).scrollTop( 0 );
}
It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:
http://www.youtube.com/watch?v=y1c7WFMMkZ4
When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.
What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.
I have used ng-idle for this and added a little logout and token null code and it is working fine, you can try this. Thanks @HackedByChinese for making such a nice module.
In IdleTimeout i have just deleted my session data and token.
Here is my code
$scope.$on('IdleTimeout', function () {
closeModals();
delete $window.sessionStorage.token;
$state.go("login");
$scope.timedout = $uibModal.open({
templateUrl: 'timedout-dialog.html',
windowClass: 'modal-danger'
});
});
Here is how you could create such a table:
SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
FROM dual
CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;
With a little bit of tweaking (i.e., replacing the ,
in [^,]
with a variable) you could write such a function to return a table.
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
Add this code somewhere, this will do the trick.
var originalVal = $.fn.val;
$.fn.val = function(){
var result =originalVal.apply(this,arguments);
if(arguments.length>0)
$(this).change(); // OR with custom event $(this).trigger('value-changed');
return result;
};
Found this solution at val() doesn't trigger change() in jQuery
For a multi-threaded problem, we needed a complex object to be built up for each thread. The object represented the data being processed, and could change depending on the user input.
Could we use a factory instead? Yes
Why didn't we? Builder makes more sense I guess.
Factories are used for creating different types of objects that are the same basic type (implement the same interface or base class).
Builders build the same type of object over and over, but the construction is dynamic so it can be changed at runtime.
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
In Package Manager Console
Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.
If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.
You can use str()
to cast it, or formatters:
"ME%d.txt" % (num,)
You can check for IsNull condition.
If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
// do something
Followed the steps.
DevKit
to path C:\Ruby193\DevKit
cd C:\Ruby192\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
Then I wrote the command
gem install rails -r -y
=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
will solve this issue.
This will search for a value in the first column to the left and return the value in the same row from a specific column.
Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):
$input = str_replace(array('.', ','), array('', '.'), $input);
and then process the numbers from there taking full advantage of PHP's loosely typed nature.
It's obvious, but the App Theme
selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone.
Just change the manifest file (AndroidManifest.xml
) is not enough because the style need to be predefined is styles.xml
. Also is useless change the layout files.
All proposed solution in Java
or Kotlin
has failed for me. Some of them crash the app. And if one never (like me) uses the title bar in app, the static solution is cleaner.
For me the only solution that works in 2019 (Android Studio 3.4.1) is:
in styles.xml
(under app/res/values) add the lines:
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
After in AndroidManifest.xml
(under app/manifests)
Replace
android:theme="@style/AppTheme">
by
android:theme="@style/AppTheme.NoActionBar">
I faced something like that in one of the old and legacy projects that i worked in that not contains any interfaces or best practice and also it's too hard to enforce them build things again or refactoring the code due to the maturity of the project business, So in my UnitTest project i used to create a Wrapper over the classes that I want to mock and that wrapper implement interface which contains all my needed methods that I want to setup and work with, Now I can mock the wrapper instead of the real class.
For Example:
Service you want to test which not contains virtual methods or implement interface
public class ServiceA{
public void A(){}
public String B(){}
}
Wrapper to moq
public class ServiceAWrapper : IServiceAWrapper{
public void A(){}
public String B(){}
}
The Wrapper Interface
public interface IServiceAWrapper{
void A();
String B();
}
In the unit test you can now mock the wrapper:
public void A_Run_ChangeStateOfX()
{
var moq = new Mock<IServiceAWrapper>();
moq.Setup(...);
}
This might be not the best practice, but if your project rules force you in this way, do it. Also Put all your Wrappers inside your Unit Test project or Helper project specified only for the unit tests in order to not overload the project with unneeded wrappers or adaptors.
Update: This answer from more than a year but in this year i faced a lot of similar scenarios with different solutions. For example it's so easy to use Microsoft Fake Framework to create mocks, fakes and stubs and even test private and protected methods without any interfaces. You can read: https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
In addition set the proxy for the command line session Open a command line where you might want to run your script
netsh winhttp set proxy YourProxySERVER:yourProxyPORT
run your script in that terminal.
Reduce() is..
It was ..
let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6
Change to
let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);
Also you can use in
let array=[5,4,19,2,7];
function findMax(acc,val)
{
if(val>acc){
acc=val;
}
}
let biggest=arrays.reduce(findMax); // 19
arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
v = 0
for i in range(len(arr)):
v = v ^ arr[i]
print(value) //6
its a matter of speed. using the iterator accesses the elements faster. a similar question was answered here:
What's faster, iterating an STL vector with vector::iterator or with at()?
Edit: speed of access varies with each cpu and compiler
My solution as SymLinks did not work on my server so I used an If in my PHP.
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$redirect = str_replace("www.", "", curPageURL());
$remove_http_root = str_replace('http://', '', $redirect);
$split_url_array = explode('/', $remove_http_root );
if($split_url_array[0] == "olddomain.com"){
header("Location: http://www.newdomain.com/$split_url_array[1]");
die();
}
To address why CMD is designed to run only one service per container, let's just realize what would happen if the secondary servers run in the same container are not trivial / auxiliary but "major" (e.g. storage bundled with the frontend app). For starters, it would break down several important containerization features such as horizontal (auto-)scaling and rescheduling between nodes, both of which assume there is only one application (source of CPU load) per container. Then there is the issue of vulnerabilities - more servers exposed in a container means more frequent patching of CVEs...
So let's admit that it is a 'nudge' from Docker (and Kubernetes/Openshift) designers towards good practices and we should not reinvent workarounds (SSH is not necessary - we have docker exec / kubectl exec / oc rsh
designed to replace it).
Swift 4:
Use synchronousRemoteObjectProxyWithErrorHandler
instead of remoteObjectProxy
when creating the remote object. No more need for a semaphore.
Below example will return the version received from the proxy. Without the synchronousRemoteObjectProxyWithErrorHandler
it will crash (trying to access non accessible memory):
func getVersion(xpc: NSXPCConnection) -> String
{
var version = ""
if let helper = xpc.synchronousRemoteObjectProxyWithErrorHandler({ error in NSLog(error.localizedDescription) }) as? HelperProtocol
{
helper.getVersion(reply: {
installedVersion in
print("Helper: Installed Version => \(installedVersion)")
version = installedVersion
})
}
return version
}
I have faced the same issue related to Strings equality check, One of the comparing string has ASCII character code 128-255.
i.e., Non-breaking space - [Hex - A0] Space [Hex - 20]. To show Non-breaking space over HTML. I have used the following
spacing entities
. Their character and its bytes are like&emsp is very wide space[ ]{-30, -128, -125}, &ensp is somewhat wide space[ ]{-30, -128, -126}, &thinsp is narrow space[ ]{32} , Non HTML Space {}
String s1 = "My Sample Space Data", s2 = "My Sample Space Data"; System.out.format("S1: %s\n", java.util.Arrays.toString(s1.getBytes())); System.out.format("S2: %s\n", java.util.Arrays.toString(s2.getBytes()));
Output in Bytes:
S1: [77, 121,
32
, 83, 97, 109, 112, 108, 101,32
, 83, 112, 97, 99, 101,32
, 68, 97, 116, 97] S2: [77, 121,-30, -128, -125
, 83, 97, 109, 112, 108, 101,-30, -128, -125
, 83, 112, 97, 99, 101,-30, -128, -125
, 68, 97, 116, 97]
Use below code for Different Spaces and their Byte-Codes: wiki for List_of_Unicode_characters
String spacing_entities = "very wide space,narrow space,regular space,invisible separator";
System.out.println("Space String :"+ spacing_entities);
byte[] byteArray =
// spacing_entities.getBytes( Charset.forName("UTF-8") );
// Charset.forName("UTF-8").encode( s2 ).array();
{-30, -128, -125, 44, -30, -128, -126, 44, 32, 44, -62, -96};
System.out.println("Bytes:"+ Arrays.toString( byteArray ) );
try {
System.out.format("Bytes to String[%S] \n ", new String(byteArray, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
? ASCII transliterations of Unicode string for Java. unidecode
String initials = Unidecode.decode( s2 );
? using Guava
: Google Core Libraries for Java
.
String replaceFrom = CharMatcher.WHITESPACE.replaceFrom( s2, " " );
For URL encode for the space use Guava laibrary.
String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);
? To overcome this problem used String.replaceAll()
with some RegularExpression
.
// \p{Z} or \p{Separator}: any kind of whitespace or invisible separator.
s2 = s2.replaceAll("\\p{Zs}", " ");
s2 = s2.replaceAll("[^\\p{ASCII}]", " ");
s2 = s2.replaceAll(" ", " ");
? Using java.text.Normalizer.Form. This enum provides constants of the four Unicode normalization forms that are described in Unicode Standard Annex #15 — Unicode Normalization Forms and two methods to access them.
s2 = Normalizer.normalize(s2, Normalizer.Form.NFKC);
Testing String and outputs on different approaches like ? Unidecode, Normalizer, StringUtils.
String strUni = "Thïs iš â funky Štring Æ,Ø,Ð,ß";
// This is a funky String AE,O,D,ss
String initials = Unidecode.decode( strUni );
// Following Produce this o/p: Th^i¨s^ i~s? a^ fu°n?k¸y^ S?t?r´i?n´g? Æ,Ø,Ð,ß
String temp = Normalizer.normalize(strUni, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
temp = pattern.matcher(temp).replaceAll("");
String input = org.apache.commons.lang3.StringUtils.stripAccents( strUni );
Using Unidecode is the best choice
, My final Code shown below.
public static void main(String[] args) {
String s1 = "My Sample Space Data", s2 = "My Sample Space Data";
String initials = Unidecode.decode( s2 );
if( s1.equals(s2)) { //[ , ] %A0 - %2C - %20 « http://www.ascii-code.com/
System.out.println("Equal Unicode Strings");
} else if( s1.equals( initials ) ) {
System.out.println("Equal Non Unicode Strings");
} else {
System.out.println("Not Equal");
}
}
It is a <p>
element that creates the top margin. You removed all top margins except of that element.
$oblast = Oblast::all();
$category = Category::where('slug', $catName)->first();
$availableProjects = $category->availableProjects;
return view('pages.business-area')->with(array('category'=>$category, 'availableProjects'=>$availableProjects, 'oblast'=>$oblast));
You get that message because you made changes in your local master and you didn't push them to remote. You have several ways to "solve" it and it normally depends on how your workflow looks like:
git push origin
assuming origin is your remotegit reset --hard origin/master
The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.
(Shame about the layout table in the first example)
Just a little addition:
I believe it's a common and known thing to add exit;
after the header function in case we don't want the rest of the code to load or execute...
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
from the man page
linux$ man -S 5 crontab
cron(8) examines cron entries once every minute.
The time and date fields are:
field allowed values
----- --------------
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sun, or use names)
...
# run five minutes after midnight, every day
5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
...
It is good to note the special "nicknames" that can be used (documented in the man page), particularly "@reboot" which has no time and date alternative.
# Run once after reboot.
@reboot /usr/local/sbin/run_only_once_after_reboot.sh
You can also use this trick to run your cron job multiple times per minute.
# Run every minute at 0, 20, and 40 second intervals
* * * * * sleep 00; /usr/local/sbin/run_3times_per_minute.sh
* * * * * sleep 20; /usr/local/sbin/run_3times_per_minute.sh
* * * * * sleep 40; /usr/local/sbin/run_3times_per_minute.sh
To add a cron job, you can do one of three things:
add a command to a user's crontab, as shown above (and from the crontab, section 5, man page).
crontab -e -u <username>
crontab -e
EDITOR
environment variable
env EDITOR=nano crontab -e -u <username>
export EDITOR=vim
crontab -e
chmod a+x <file>
create a script/program as a cron job, and add it to the system's anacron /etc/cron.*ly
directories
chmod a+x /etc/cron.daily/script_runs_daily.sh
-- make it executableman anacron
chmod a+x <file>
/etc/crontab
or /etc/anacrontab
to run at a set time/etc/anacrontab
, and define cron.hourly in /etc/cron.d/0hourly
Or, One can create system crontables in /etc/cron.d
.
/etc/cron.d
do not need to be executable.someuser
, and the use of /bin/bash
as the shell is forced. File: /etc/cron.d/myapp-cron
# use /bin/bash to run commands, no matter what /etc/passwd says
SHELL=/bin/bash
# Execute a nightly (11:00pm) cron job to scrub application records
00 23 * * * someuser /opt/myapp/bin/scrubrecords.php
The building blocks of REST are mainly the resources (and URI) and the hypermedia. In this context, GET
is the way to get a representation of the resource (which can indeed be mapped to a SELECT
in CRUD terms).
However, you shouldn't necessarily expect a one-to-one mapping between CRUD operations and HTTP verbs.
The main difference between PUT
and POST
is about their idempotent property. POST
is also more commonly used for partial updates, as PUT
generally implies sending a full new representation of the resource.
I'd suggest reading this:
The HTTP specification is also a useful reference:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI.
[...]
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
Why work harder than you have to? postForEntity
accepts a simple Map
object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:
@Test
public void shouldLoginSuccessfully() {
// 'restTemplate' below has been @Autowired prior to this
Map map = new HashMap<String, String>();
map.put("username", "bob123");
map.put("password", "myP@ssw0rd");
ResponseEntity<Void> resp = restTemplate.postForEntity(
"http://localhost:8000/login",
map,
Void.class);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}
I have a suspicion, that the Answer doesn't give the correct result. In the question the asker wants to convert timestamp from server to current time in Hellsinki disregarding current time zone of the user.
It's the fact that the user's timezone can be what ever so we cannot trust to it.
If eg. timestamp is 1270544790922 and we have a function:
var _date = new Date();
_date.setTime(1270544790922);
var _helsenkiOffset = 2*60*60;//maybe 3
var _userOffset = _date.getTimezoneOffset()*60*60;
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);
When a New Yorker visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 05:21:02 GMT-0400 (EDT)
And when a Finlander visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 11:55:50 GMT+0300 (EEST)
So the function is correct only if the page visitor has the target timezone (Europe/Helsinki) in his computer, but fails in nearly every other part of the world. And because the server timestamp is usually UNIX timestamp, which is by definition in UTC, the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), we cannot determine DST or non-DST from timestamp.
So the solution is to DISREGARD the current time zone of the user and implement some way to calculate UTC offset whether the date is in DST or not. Javascript has not native method to determine DST transition history of other timezone than the current timezone of user. We can achieve this most simply using server side script, because we have easy access to server's timezone database with the whole transition history of all timezones.
But if you have no access to the server's (or any other server's) timezone database AND the timestamp is in UTC, you can get the similar functionality by hard coding the DST rules in Javascript.
To cover dates in years 1998 - 2099 in Europe/Helsinki you can use the following function (jsfiddled):
function timestampToHellsinki(server_timestamp) {
function pad(num) {
num = num.toString();
if (num.length == 1) return "0" + num;
return num;
}
var _date = new Date();
_date.setTime(server_timestamp);
var _year = _date.getUTCFullYear();
// Return false, if DST rules have been different than nowadays:
if (_year<=1998 && _year>2099) return false;
// Calculate DST start day, it is the last sunday of March
var start_day = (31 - ((((5 * _year) / 4) + 4) % 7));
var SUMMER_start = new Date(Date.UTC(_year, 2, start_day, 1, 0, 0));
// Calculate DST end day, it is the last sunday of October
var end_day = (31 - ((((5 * _year) / 4) + 1) % 7))
var SUMMER_end = new Date(Date.UTC(_year, 9, end_day, 1, 0, 0));
// Check if the time is between SUMMER_start and SUMMER_end
// If the time is in summer, the offset is 2 hours
// else offset is 3 hours
var hellsinkiOffset = 2 * 60 * 60 * 1000;
if (_date > SUMMER_start && _date < SUMMER_end) hellsinkiOffset =
3 * 60 * 60 * 1000;
// Add server timestamp to midnight January 1, 1970
// Add Hellsinki offset to that
_date.setTime(server_timestamp + hellsinkiOffset);
var hellsinkiTime = pad(_date.getUTCDate()) + "." +
pad(_date.getUTCMonth()) + "." + _date.getUTCFullYear() +
" " + pad(_date.getUTCHours()) + ":" +
pad(_date.getUTCMinutes()) + ":" + pad(_date.getUTCSeconds());
return hellsinkiTime;
}
Examples of usage:
var server_timestamp = 1270544790922;
document.getElementById("time").innerHTML = "The timestamp " +
server_timestamp + " is in Hellsinki " +
timestampToHellsinki(server_timestamp);
server_timestamp = 1349841923 * 1000;
document.getElementById("time").innerHTML += "<br><br>The timestamp " +
server_timestamp + " is in Hellsinki " + timestampToHellsinki(server_timestamp);
var now = new Date();
server_timestamp = now.getTime();
document.getElementById("time").innerHTML += "<br><br>The timestamp is now " +
server_timestamp + " and the current local time in Hellsinki is " +
timestampToHellsinki(server_timestamp);?
And this print the following regardless of user timezone:
The timestamp 1270544790922 is in Hellsinki 06.03.2010 12:06:30
The timestamp 1349841923000 is in Hellsinki 10.09.2012 07:05:23
The timestamp is now 1349853751034 and the current local time in Hellsinki is 10.09.2012 10:22:31
Of course if you can return timestamp in a form that the offset (DST or non-DST one) is already added to timestamp on server, you don't have to calculate it clientside and you can simplify the function a lot. BUT remember to NOT use timezoneOffset(), because then you have to deal with user timezone and this is not the wanted behaviour.
Just put in fg
and go back to your most recently suspended program.
You can use Socket.io tester, this app lets you connect to a socket.io server and subscribe to a certain topic and/or lets you send socket messages to the server
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
<MyComponent />
compiles to React.createElement(MyComponent, {})
, which expects a string (HTML tag) or a function (ReactClass) as first parameter.
You could just store your component class in a variable with a name that starts with an uppercase letter. See HTML tags vs React Components.
var MyComponent = Components[type + "Component"];
return <MyComponent />;
compiles to
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified
It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:
iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.
The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.
Update:
There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.
http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
Return a list of the words in the string, using sep as the delimiter ... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>>
list.sort(Comparator.comparing(o -> o.getDateTime()));
The best answer IMHO from Tunaki using Java 8 lambda
Noting down my situation here may be useful to somebody,
I have to send a custom intent with multiple intent extras to a broadcast receiver in Android P,
The details are,
Receiver name: com.hardian.testservice.TestBroadcastReceiver
Intent action = "com.hardian.testservice.ADD_DATA"
intent extras are,
Run the following in command line.
adb shell "am broadcast -a com.hardian.testservice.ADD_DATA --es text 'test msg' --es source 1 -n com.hardian.testservice/.TestBroadcastReceiver"
Hope this helps.
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
Another way that allows you to change the text of "Delete" and add more buttons when sliding a cell is to use editActionsForRowAtIndexPath
.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var deleteAction = UITableViewRowAction(style: .Default, title: "Delete") {action in
//handle delete
}
var editAction = UITableViewRowAction(style: .Normal, title: "Edit") {action in
//handle edit
}
return [deleteAction, editAction]
}
canEditRowAtIndexPath
and commitEditingStyle
are still required, but you can leave commitEditingStyle
empty since deletion is handled in editActionsForRowAtIndexPath
.
You can try:
WebElement getmenu= driver.findElement(By.xpath("//*[@id='ui-id-2']/span[2]")); //xpath the parent
Actions act = new Actions(driver);
act.moveToElement(getmenu).perform();
Thread.sleep(3000);
WebElement clickElement= driver.findElement(By.linkText("Sofa L"));//xpath the child
act.moveToElement(clickElement).click().perform();
If you had case the web have many category, use the first method. For menu you wanted, you just need the second method.
Make sure you don't have a blank index.html file in your root folder. It happens :)
For camera access use:
<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>
I didn't take the time to test out every answer on here, but nothing seems as simple and as efficient as this:
DECLARE @WeekNum int
DECLARE @YearNum char(4)
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @YearNum) + (@WeekNum-1), 6) AS StartOfWeek
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @YearNum) + (@WeekNum-1), 5) AS EndOfWeek
Try this for a unique list.
ping -c 5 -b 10.10.0.255 | grep 'bytes from' | awk '{ print $4 }' | sort | uniq
another method (fetches live hosts):
fping -ag 192.168.1.0/24
var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
var cars = [
"volvo",
"saab",
"mercedes",
"audi"
];
var options_str = "";
cars.forEach( function(car) {
options_str += '<option value="' + car + '">' + car + '</option>';
});
sel.innerHTML = options_str;
window.onload = function() {
document.body.appendChild(sel);
};
From the jQuery.each() documentation:
.each( function(index, Element) )
function(index, Element)A function to execute for each matched element.
So you'll want to use:
$('#list option').each(function(i,e){
//do stuff
});
...where index will be the index and element will be the option element in list
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
you should try using os.walk
yourpath = 'path'
import os
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
print(os.path.join(root, name))
stuff
for name in dirs:
print(os.path.join(root, name))
stuff
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
Try this:
dbConfig.php
<?php
$mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name');
if($mysqli->connect_error)
{
echo $mysqli->connect_error;
}
?>
Index.php
<html>
<head><title>Inserting data in database table </title>
</head>
<body>
<form action="control_table.php" method="post">
<table border="1" background="red" align="center">
<tr>
<td>Login Name</td>
<td><input type="text" name="txtname" /></td>
</tr>
<br>
<tr>
<td>Password</td>
<td><input type="text" name="txtpwd" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="txtbutton" value="SUBMIT" /></td>
</tr>
</table>
control_table.php
<?php include 'config.php'; ?>
<?php
$name=$pwd="";
if(isset($_POST['txtbutton']))
{
$name = $_POST['txtname'];
$pwd = $_POST['txtpwd'];
$mysqli->query("insert into users(name,pwd) values('$name', '$pwd')");
if(!$mysqli)
{ echo mysqli_error(); }
else
{
echo "Successfully Inserted <br />";
echo "<a href='show.php'>View Result</a>";
}
}
?>
If you find the onCreateOptionsMenu(Menu menu, MenuInflater inflater)
method is not being invoked, make sure you call the following from the Fragment's onCreate(Bundle savedInstanceState)
method:
setHasOptionsMenu(true)
Cast the operands to floats:
float ans = (float)a / (float)b;
The best thing hands down that I have tried is LINQ to XSD (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still "Preview", I have not encountered any bugs with it.
If you have an XSD Schema that looks like this:
<xs:element name="RootElement">
<xs:complexType>
<xs:sequence>
<xs:element name="Element1" type="xs:string" />
<xs:element name="Element2" type="xs:string" />
</xs:sequence>
<xs:attribute name="Attribute1" type="xs:integer" use="optional" />
<xs:attribute name="Attribute2" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
Then you can simply build XML like this:
RootElement rootElement = new RootElement;
rootElement.Element1 = "Element1";
rootElement.Element2 = "Element2";
rootElement.Attribute1 = 5;
rootElement.Attribute2 = true;
Or simply load an XML from file like this:
RootElement rootElement = RootElement.Load(filePath);
Or save it like this:
rootElement.Save(string);
rootElement.Save(textWriter);
rootElement.Save(xmlWriter);
rootElement.Untyped
also yields the element in form of a XElement (from LINQ to XML).
please try this way with filter
angular.module('myApp')
.filter('isEmpty', function () {
var bar;
return function (obj) {
for (bar in obj) {
if (obj.hasOwnProperty(bar)) {
return false;
}
}
return true;
};
});
usage:
<p ng-hide="items | isEmpty">Some Content</p>
Via from : Checking if object is empty, works with ng-show but not from controller?
remote(repository url alias) ? origin(upstream alias) ? master(branch alias);
remote
, level same as working directory
, index
, repository
,
origin
, local repository branch map to remote repository branch
We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.
HTML
<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />
JS Code
//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");
//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)
if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
ajaxRequestVariable.abort();
$("#test").html("Ajax Request Cancelled.");
}
});
//Ajax Process Starts
ajaxRequestVariable = $.ajax({
method: "POST",
url: '/echo/json/',
contentType: "application/json",
cache: false,
dataType: "json",
data: {
json: JSON.encode({
data:
[
{"prop1":"prop1Value"},
{"prop1":"prop2Value"}
]
}),
delay: 11
},
success: function (response) {
$("#test").show();
$("#test").html("Request is completed");
},
error: function (error) {
},
complete: function () {
}
});
I have written a generic caching func()
which will cache any variable easily and very readable format.
Caching function:
function calculateSomethingMaybe(args){
return args;
}
function caching(fn){
const cache = {};
return function(){
const string = arguments[0];
if(!cache[string]){
const result = fn.apply(this, arguments);
cache[string] = result;
return result;
}
return cache[string];
}
}
const letsCache = caching(calculateSomethingMaybe);
console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));
Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!
A key difference going forward is the release schedule and support policy.
OpenJDK will have a feature release every 6 months which is only supported until the next feature release. It's essentially a continuous stream of releases targeted to developers.
The Oracle JDK is targeted more towards an enterprise audience which values stability. It's based on one of the OpenJDK releases but is then given long term support (LTS). The Oracle JDK has releases planned every 3 years.
SQL> select * from stud;
STUDENTID NAME DETAILS
---------- ------------------------------ ------------------------------
1 Alfred AA
2 Betty BB
3 Chris CC
SQL> select * from subject;
SUBJECTID NAME
---------- ------------------------------
1 Maths
2 Science
3 English
SQL> select * from marks;
STUDENTID SUBJECTID MARK
---------- ---------- ----------
1 1 61
1 2 75
1 3 87
2 1 82
2 2 64
2 3 77
3 1 82
3 2 83
3 3 67
9 rows selected.
SQL> select name, subjectid, mark
2 from (select name, subjectid, mark, dense_rank() over(partition by subjectid order by mark desc) rank
3 from stud st, marks mk
4 where st.studentid=mk.studentid)
5 where rank=1;
NAME SUBJECTID MARK
------------------------------ ---------- ----------
Betty 1 82
Chris 1 82
Chris 2 83
Alfred 3 87
SQL>
Instead of configuring Tomcat to redirect requests, use Apache as a frontend with the Apache Tomcat connector so that Apache is only serving static content, while asking tomcat for dynamic content.
Using the JKmount directive (or others) you could specify exactly which requests are sent to Tomcat.
Requests for static content, such as images, would be served directly by Apache, using a standard virtual host configuration, while other requests, defined in the JKMount directive will be sent to Tomcat workers.
I think this implementation would give you the most flexibility and control on the overall application.
There's always a lowercase "v". But seriously, aside from Unicode, all I can find would be &darr
, which looks like ↓.
Try this: getActivity().runOnUiThread(new Runnable...
It's because:
1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.
2) Fragment doesn't have runOnUiThread.
However, Activity does.
Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:
// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());
// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.
Use CSS to remove text-decoration
s.
a {
text-decoration: none;
}
I had the same probem a while ago, before starting using Symfony framework.
Just use a function __() which has arameters pageId (or objectId, objectTable described in #2), target language and an optional parameter of fallback (default) language. The default language could be set in some global config in order to have an easier way to change it later.
For storing the content in database i used following structure: (pageId, language, content, variables).
pageId would be a FK to your page you want to translate. if you have other objects, like news, galleries or whatever, just split it into 2 fields objectId, objectTable.
language - obviously it would store the ISO language string EN_en, LT_lt, EN_us etc.
content - the text you want to translate together with the wildcards for variable replacing. Example "Hello mr. %%name%%. Your account balance is %%balance%%."
variables - the json encoded variables. PHP provides functions to quickly parse these. Example "name: Laurynas, balance: 15.23".
you mentioned also slug field. you could freely add it to this table just to have a quick way to search for it.
Your database calls must be reduced to minimum with caching the translations. It must be stored in PHP array, because it is the fastest structure in PHP language. How you will make this caching is up to you. From my experience you should have a folder for each language supported and an array for each pageId. The cache should be rebuilt after you update the translation. ONLY the changed array should be regenerated.
i think i answered that in #2
your idea is perfectly logical. this one is pretty simple and i think will not make you any problems.
URLs should be translated using the stored slugs in the translation table.
Final words
it is always good to research the best practices, but do not reinvent the wheel. just take and use the components from well known frameworks and use them.
take a look at Symfony translation component. It could be a good code base for you.
Since the static method 'GetAccessControl' seems to be missing from the present version of .Net core/Standard I had to modify @Bryce Wagner's answer (I went ahead and used more modern syntax):
public static class PermissionHelper
{
public static bool? CurrentUserHasWritePermission(string filePath)
=> new WindowsPrincipal(WindowsIdentity.GetCurrent())
.SelectWritePermissions(filePath)
.FirstOrDefault();
private static IEnumerable<bool?> SelectWritePermissions(this WindowsPrincipal user, string filePath)
=> from rule in filePath
.GetFileSystemSecurity()
.GetAccessRules(true, true, typeof(NTAccount))
.Cast<FileSystemAccessRule>()
let right = user.HasRightSafe(rule)
where right.HasValue
// Deny takes precedence over allow
orderby right.Value == false descending
select right;
private static bool? HasRightSafe(this WindowsPrincipal user, FileSystemAccessRule rule)
{
try
{
return user.HasRight(rule);
}
catch
{
return null;
}
}
private static bool? HasRight(this WindowsPrincipal user,FileSystemAccessRule rule )
=> rule switch
{
{ FileSystemRights: FileSystemRights fileSystemRights } when (fileSystemRights &
(FileSystemRights.WriteData | FileSystemRights.Write)) == 0 => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") &&
!user.IsInRole(new SecurityIdentifier(rule.IdentityReference.Value)) => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") == false &&
!user.IsInRole(rule.IdentityReference.Value) => null,
{ AccessControlType: AccessControlType.Deny } => false,
{ AccessControlType: AccessControlType.Allow } => true,
_ => null
};
private static FileSystemSecurity GetFileSystemSecurity(this string filePath)
=> new FileInfo(filePath) switch
{
{ Exists: true } fileInfo => fileInfo.GetAccessControl(),
{ Exists: false } fileInfo => (FileSystemSecurity)fileInfo.Directory.GetAccessControl(),
_ => throw new Exception($"Check the file path, {filePath}: something's wrong with it.")
};
}
People have mentioned make
but bjam
also supports a similar concept. Using bjam -jx
instructs bjam to build up to x
concurrent commands.
We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.
Swift 5
import SystemConfiguration
protocol Utilities {}
extension NSObject: Utilities {
enum ReachabilityStatus {
case notReachable
case reachableViaWWAN
case reachableViaWiFi
}
var currentReachabilityStatus: ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return .notReachable
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .notReachable
}
if flags.contains(.reachable) == false {
// The target host is not reachable.
return .notReachable
}
else if flags.contains(.isWWAN) == true {
// WWAN connections are OK if the calling application is using the CFNetwork APIs.
return .reachableViaWWAN
}
else if flags.contains(.connectionRequired) == false {
// If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
return .reachableViaWiFi
}
else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
// The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
return .reachableViaWiFi
}
else {
return .notReachable
}
}
}
In any method use the below condition
if currentReachabilityStatus == .notReachable {
// Network Unavailable
} else {
// Network Available
}
For the best practice - use style="display:"
it will work every where..
Concerning the answer by BoltClock and John, I personally had issues with the initial keyword when using IE11. It works fine in Chrome, but in IE it seems to have no effect.
According to this answer IE does not support the initial keyword: Div display:initial not working as intended in ie10 and chrome 29
I tried setting it blank instead as suggested here: how to revert back to normal after display:none for table row
This worked and was good enough for my scenario. Of course to set the real initial value the above answer is the only good one I could find.
You can use the contenteditable attribute on the cells, rows, or table in question.
Updated for IE8 compatibility
<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>
Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.
You'd also need to check whether your target audience's browsers supported this attribute.
As far as listening for the changes (so you can send to the server), see contenteditable change events
You can use ExcelDataReader to read existing Excel
file:
using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
var value = reader.GetValue(i)?.ToString();
}
}
}
}
After you collected all data needed you can try my SwiftExcel library to export it to the new Excel
file:
using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
for (var i = 1; i < 10; i++)
{
ew.Write("your_data", i, 1);
}
}
Nuget commands to install both libraries:
Install-Package ExcelDataReader
Install-Package SwiftExcel
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
I ran to a similar error running Excel in VBA, what I've learned is that when I pull data from MSSQL, and then using get_range
and .Value2
apply it's out of the range, any value that was of type uniqueidentifier
(GUID) resulted in this error.
Only when I cast the value to nvarcahr(max)
it worked.
You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.
SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC
As mentioned above, edit the application host.config. An easy way to find this is run your site in VS using IIS Express. Right click the systray icon, show all applications. Choose your site, and then click on the config link at the bottom to open it.
I'd suggest adding another binding entry, and leave the initial localhost one there. This additional binding will appear in the IIS Express systray as a separate application under the site.
To avoid having to run VS as admin (lots of good reasons not to run as admin), add a netsh rule as follows (obviously replacing the IP and port with your values) - you'll need an admin cmd.exe for this, it only needs to be run once:
netsh http add urlacl url=http://192.168.1.121:51652/ user=\Everyone
netsh can add rules like url=http://+:51652/ but I failed to get this to place nicely with IIS Express. You can use netsh http show urlacl
to list existing rules, and they can be deleted with netsh http delete urlacl url=blah
.
Further info: http://msdn.microsoft.com/en-us/library/ms733768.aspx
First you need to prepare your url to accept the param in the regex: (urls.py)
url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),
So you use this in your template:
{% url 'panel_person_form' person_id=item.id %}
If you have more than one param, you can change your regex and modify the template using the following:
{% url 'panel_person_form' person_id=item.id group_id=3 %}
Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
For Chrome via Chrome Fullscreen API
Note that for (Chrome) security reasons it cannot be called or executed automatically, there must be an interaction from the user first. (Such as button click, keydown/keypress etc.)
addEventListener("click", function() {
var
el = document.documentElement
, rfs =
el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
;
rfs.call(el);
});
Javascript Fullscreen API as demo'd by David Walsh that seems to be a cross browser solution
// Find the right method, call on correct element
function launchFullScreen(element) {
if(element.requestFullScreen) {
element.requestFullScreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
}
}
// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element
Simply use the print function to echo text in the PHP file as follows:
<?php
print('
<div class="wrap">
<span class="textClass">TESTING</span>
</div>
')
?>
You can improve the speed of your code if you restrict the items jQuery will look at.
Use the selector :input instead of * to achieve it.
$('#divId :input').serialize()
This will make your code faster because the list of items is shorter.
Check the setting in your user config /home/username/.netbeans/version/etc/netbeans.conf
I had the problem where I was specifying the location globally, but my user setting was overriding the global setting.
CentOS 7/Netbeans 8.1
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
You can use the cmath module.
If the number is converted to a complex format, then it becomes easier to just call the polar method on the number.
import cmath
input_num = complex(1, 2) # stored as 1+2j
r, phi = cmath.polar(input_num)
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
I had this issue and it turned out that one project was pointing to SQLExpress but the one with the problem was pointing to LocalDb. (in their respective web.config). Silly oversight but worth noting here in case anyone else is troubleshooting this issue.
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
Since you say you're using Java 5, you can use setInt
with an Integer
due to autounboxing: pstmt.setInt(1, tempID)
should work just fine. In earlier versions of Java, you would have had to call .intValue()
yourself.
The opposite works as well... assigning an int
to an Integer
will automatically cause the int
to be autoboxed using Integer.valueOf(int)
.
This is what the official Anaconda documentation recommends:
conda update conda
conda update anaconda=2020.07
If the second line throws an error (typo in the documentation?) this worked here:
conda install anaconda=2020.07
(You can find all version specifier here.)
The command will update to a specific release of the Anaconda meta-package.
This is, IMHO, what 95% of Anaconda users want. Simply upgrading to the latest version of the Anaconda meta-package (put together and tested by the Anaconda Distributors) and not caring about the update status of individual packages (which would be issued by conda update --all
).
If you're executing the query and expecting a ResultSet
(you are in this scenario, at least) then you can simply call ResultSet
's getStatement()
like so:
ResultSet rs = pstmt.executeQuery();
String executedQuery = rs.getStatement().toString();
The variable executedQuery
will contain the statement that was used to create the ResultSet
.
Now, I realize this question is quite old, but I hope this helps someone..
Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function".
Now the syntax problem: because functions returns values, how can you return a function and not it's returning value?
by omitting brackets! Because without brackets, the function won't be executed! So:
return b;
Will return the "function" (imagine it like if you are returning a number), while:
return b();
First executes the function then return the value obtained by executing it, it's a big difference!
Definitely makes a difference: How To… Speed up Gradle build time
Just create a file named gradle.properties
in the following directory:
/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)
Add this line to the file:
org.gradle.daemon=true
I recommend use boolean;
. You have to install the boolean module from cpan though.
Using file
command with the --mime-encoding
option (e.g. file --mime-encoding some_file.txt
) instead of the -I option works on OS X and has the added benefit of omitting the mime type, "text/plain", which you probably don't care about.
An even cleaner python3 compatible version that doesn't insert but appends & reverses:
def tail(f, window=1):
"""
Returns the last `window` lines of file `f` as a list of bytes.
"""
if window == 0:
return b''
BUFSIZE = 1024
f.seek(0, 2)
end = f.tell()
nlines = window + 1
data = []
while nlines > 0 and end > 0:
i = max(0, end - BUFSIZE)
nread = min(end, BUFSIZE)
f.seek(i)
chunk = f.read(nread)
data.append(chunk)
nlines -= chunk.count(b'\n')
end -= nread
return b'\n'.join(b''.join(reversed(data)).splitlines()[-window:])
use it like this:
with open(path, 'rb') as f:
last_lines = tail(f, 3).decode('utf-8')
function containsAny(source,target)_x000D_
{_x000D_
var result = source.filter(function(item){ return target.indexOf(item) > -1}); _x000D_
return (result.length > 0); _x000D_
} _x000D_
_x000D_
_x000D_
//results_x000D_
_x000D_
var fruits = ["apple","banana","orange"];_x000D_
_x000D_
_x000D_
console.log(containsAny(fruits,["apple","grape"]));_x000D_
_x000D_
console.log(containsAny(fruits,["apple","banana","pineapple"]));_x000D_
_x000D_
console.log(containsAny(fruits,["grape", "pineapple"]));
_x000D_
I tried everything but I found a solution which really works. It creates independed solution with a new namespace name an so on.
In main form find namespace name -> right click -> Refactor -> Rename and select a new name. Check all boxes and click OK.
In the solution explorer rename solution name to a new name.
In the solution explorer rename project name to a new name.
Close VS and rename folder (in total commander for example) in the solution folder to a new name.
In .sln file rename old name to a new name.
Delete old .suo files (hidden)
Start VS and load project
Project -> properties -> change Assembly name and default namespace to a new name.
Okay. I don't know how but this worked.
First I cleaned the project and then, running the project made everything go alright.
Inshort, First Clean
and then Run
.
Edit First Clean
and then Make Project
also works.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.
Here's a cut and paste of the code, which worked for me:
function countProperties(obj) {
var prop;
var propCount = 0;
for (prop in obj) {
propCount++;
}
return propCount;
}
This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.
Received this error while using the openAM Fedlet on IIS7
Changing the user account for the default website resolved the issue. Ideally, you would want this to be a service account. Perhaps even the IUSR account. Suggest looking up methods for IIS hardening to nail it down completely.
AWS4-HMAC-SHA256, also known as Signature Version 4, ("V4") is one of two authentication schemes supported by S3.
All regions support V4, but US-Standard¹, and many -- but not all -- other regions, also support the other, older scheme, Signature Version 2 ("V2").
According to http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html ... new S3 regions deployed after January, 2014 will only support V4.
Since Frankfurt was introduced late in 2014, it does not support V2, which is what this error suggests you are using.
http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html explains how to enable V4 in the various SDKs, assuming you are using an SDK that has that capability.
I would speculate that some older versions of the SDKs might not support this option, so if the above doesn't help, you may need a newer release of the SDK you are using.
¹US Standard
is the former name for the S3 regional deployment that is based in the us-east-1
region. Since the time this answer was originally written,
"Amazon S3 renamed the US Standard Region to the US East (N. Virginia) Region to be consistent with AWS regional naming conventions." For all practical purposes, it's only a change in naming.
I ended up using this quick piece of code that did exactly what I needed:
final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
try {
// Open an input stream
Scanner reader = new Scanner(fc.getSelectedFile());
}
Change/Add to data-interval="false" on carousel div
<div class="carousel slide" data-ride="carousel" data-type="multi" data-interval="false" id="myCarousel">
if you happen to not have a graphical interface available you can also print out the commit graph on the command line:
git log --oneline --graph --decorate --all
if this command complains with an invalid option --oneline, use:
git log --pretty=oneline --graph --decorate --all
Here is the best way to find out Foreign Key Relationship in all Database.
exec sp_helpconstraint 'Table Name'
and one more way
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME='Table Name'
--and left(CONSTRAINT_NAME,2)='FK'(If you want single key)
From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is
DELETE FROM MainTable
WHERE PrimaryKey = ???
You database engine will take care of deleting the corresponding referencing records.
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
For my list view am using custom Adapter which extends ArrayAdapter. in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox. Ex: Activity parentActivity; Constructor for Adapter `
public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
super(context,R.layout.listdummy,data);
this.mContext = context;
this.parentActivity = parentActivity;
}
` calling Adapter from MainActivty
adapter = new CustomAdapter(dataModels,MainActivity.this,this);
_x000D_
now write ur alertdialog inside ur button which is in the Adapter class
viewHolder.update.setOnClickListener(new View.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(final View view) {_x000D_
_x000D_
_x000D_
AlertDialog.Builder alertDialog = new AlertDialog.Builder(parentActivity);_x000D_
alertDialog.setTitle("Updating");_x000D_
alertDialog.setCancelable(false);_x000D_
_x000D_
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);_x000D_
@SuppressLint("InflateParams") final View view1 = layoutInflater.inflate(R.layout.dialog,null);_x000D_
alertDialog.setView(view1);_x000D_
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(DialogInterface dialogInterface, int i) {_x000D_
dialogInterface.cancel();_x000D_
}_x000D_
});_x000D_
alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(DialogInterface dialogInterface, int i) {_x000D_
_x000D_
//ur logic_x000D_
}_x000D_
}_x000D_
});_x000D_
alertDialog.create().show();_x000D_
_x000D_
}_x000D_
});
_x000D_
Public Function connectDB() As OleDbConnection
Dim Con As New OleDbConnection
'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
Try
Con.Open()
Catch ex As Exception
showMessage(ex)
End Try
Return Con
End Function
$ mail -s "test message from centos" [email protected]
hello from centos linux command line
Ctrl+D to finish
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
Also do note when specifying DATETIME
as DATETIME(3)
or like on MySQL 5.7.x, you also have to add the same value for CURRENT_TIMESTAMP(3)
. If not it will keep throwing 'Invalid default value'.
I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData
by label instead of index:
ResultSet resultSet = null;
DatabaseMetaData metaData = null;
try {
metaData = connection.getMetaData();
resultSet = metaData.getColumns(null, null, tableName, null);
while (resultSet.next()){
String name = resultSet.getString("COLUMN_NAME");
}
}
You can define foreign key constraints on the tables with ON DELETE CASCADE
option.
Then deleting the record from parent table removes the records from child tables.
Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
I got this working.
log4j.appender.file.File=${LogFilePath}
-DLogFilePath=C:\work\MyLogFile.log
Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples
Also, you should really really really change your List
into a strongly typed list (List<T>
), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.
Just put hello()
somewhere below the function and it will execute when you do python your_file.py
For a neater solution you can use this:
if __name__ == '__main__':
hello()
That way the function will only be executed if you run the file, not when you import the file.
I can't comment but don't want to start a new thread. But this isn't working. A simple round trip:
byte[] b = new byte[]{ 0, 0, 0, -127 }; // 0x00000081
String s = new String(b,StandardCharsets.UTF_8); // UTF8 = 0x0000, 0x0000, 0x0000, 0xfffd
b = s.getBytes(StandardCharsets.UTF_8); // [0, 0, 0, -17, -65, -67] 0x000000efbfbd != 0x00000081
I'd need b[] the same array before and after encoding which it isn't (this referrers to the first answer).
If you're using a Frame (Class Extends Frame) you'll not get the
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
For any versions of SQL Server: dateadd(dd, datediff(dd, 0, getdate()), 0)
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
This makefile
will generate the 'missing separator' error message:
all
@echo NDK_PROJECT_PATH=$(NDK_PROJECT_PATH)
done:
@echo "All done"
There's a tab before the @echo "All done"
(though the done:
rule and action are largely superfluous), but not before the @echo PATH=$(PATH)
.
The trouble is that the line starting all
should either have a colon :
or an equals =
to indicate that it is a target line or a macro line, and it has neither, so the separator is missing.
The action that echoes the value of a variable must be associated with a target, possibly a dummy or PHONEY target. And that target line must have a colon on it. If you add a :
after all
in the example makefile
and replace the leading blanks on the next line by a tab, it will work sanely.
You probably have an analogous problem near line 102 in the original makefile
. If you showed 5 non-blank, non-comment lines before the echo operations that are failing, it would probably be possible to finish the diagnosis. However, since the question was asked in May 2013, it is unlikely that the broken makefile
is still available now (August 2014), so this answer can't be validated formally. It can only be used to illustrate a plausible way in which the problem occurred.
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
CSS is a nicely designed paradigm, and many of it's features are not much used.
If by a condition and variable you mean a mechanism to distribute a change of some value to the whole document, or under a scope of some element, then this is how to do it:
var myVar = 4;_x000D_
document.body.className = (myVar == 5 ? "active" : "normal");
_x000D_
body.active .menuItem {_x000D_
background-position : 150px 8px;_x000D_
background-color: black;_x000D_
}_x000D_
body.normal .menuItem {_x000D_
background-position : 4px 8px; _x000D_
background-color: green;_x000D_
}
_x000D_
<body>_x000D_
<div class="menuItem"></div>_x000D_
</body>
_x000D_
This way, you distribute the impact of the variable throughout the CSS styles. This is similar to what @amichai and @SeReGa propose, but more versatile.
Another such trick is to distribute the ID of some active item throughout the document, e.g. again when highlighting a menu: (Freemarker syntax used)
var chosenCategory = 15;_x000D_
document.body.className = "category" + chosenCategory;
_x000D_
<#list categories as cat >_x000D_
body.category${cat.id} .menuItem { font-weight: bold; }_x000D_
</#list>
_x000D_
<body>_x000D_
<div class="menuItem"></div>_x000D_
</body>
_x000D_
Sure,this is only practical with a limited set of items, like categories or states, and not unlimited sets like e-shop goods, otherwise the generated CSS would be too big. But it is especially convenient when generating static offline documents.
One more trick to do "conditions" with CSS in combination with the generating platform is this:
.myList {_x000D_
/* Default list formatting */_x000D_
}_x000D_
.myList.count0 {_x000D_
/* Hide the list when there is no item. */_x000D_
display: none;_x000D_
}_x000D_
.myList.count1 {_x000D_
/* Special treatment if there is just 1 item */_x000D_
color: gray;_x000D_
}
_x000D_
<ul class="myList count${items.size()}">_x000D_
<!-- Iterate list's items here -->_x000D_
<li>Something...</div>_x000D_
</ul>
_x000D_
If you are using push to push the data to the option.series dynamically .. just use
options.series = [];
to clear it.
options.series = [];
$("#change").click(function(){
}
Mby bootstrap img-responsive
class is you looking for.
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
This answer explains the why behind this behavior.
Any approach to render the script
tag doesn't work as expected:
script
tag for external scriptsdangerouslySetInnerHTML
React DOM (the renderer for react on web) uses createElement
calls to render JSX into DOM elements.
createElement
uses the innerHTML
DOM API to finally add these to the DOM (see code in React source). innerHTML
does not execute script
tag added as a security consideration. And this is the reason why in turn rendering script
tags in React doesn't work as expected.
For how to use script
tags in React check some other answers on this page.
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.>>> sys.stdout.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1
Observing the example above:
sys.stdout.write
won't write non-string object, but print
will
sys.stdout.write
won't add a new line symbol in the end, but print
will
If we dive deeply,
sys.stdout
is a file object which can be used for the output of print()
if file argument of print()
is not specified, sys.stdout
will be used
this should do it:
if (arrayList != null && !arrayList.isEmpty()) {
T item = arrayList.get(arrayList.size()-1);
}
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
Look at ~/.myslgui/query-browser/history.xml
here you can find the last queries made with mysql_query_browser
(some days old)
$characters = '123456789';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$pin=$randomString;
~/.vimrc
file
" highlight the searched items
set hlsearch
" F8 search for word under the cursor recursively , :copen , to close -> :ccl
nnoremap <F8> :grep! "\<<cword>\>" . -r<CR>:copen 33<CR>
:so%
In normal model go over the word.
Press * Press F8 to search recursively bellow your whole project over the word
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
SELECT * FROM Table
WHERE ID = (
SELECT IDENT_CURRENT('Table'))
SELECT * FROM Table
WHERE ID = (
SELECT MAX(ID) FROM Table)
SELECT TOP 1 * FROM Table
ORDER BY ID DESC
But the first one will be more efficient because no index scan is needed (if you have index on Id column).
The second one solution is equivalent to the third (both of them need to scan table to get max id).
Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.
There's an example (and more info) in the jersey user guide, which I copy here:
POJO with JAXB annotations:
@XmlRootElement
public class Planet {
public int id;
public String name;
public double radius;
}
Resource:
@Path("planet")
public class Resource {
@GET
@Produces(MediaType.APPLICATION_XML)
public Planet getPlanet() {
Planet p = new Planet();
p.id = 1;
p.name = "Earth";
p.radius = 1.0;
return p;
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(Planet p) {
System.out.println("setPlanet " + p.name);
}
}
The xml that gets produced/consumed:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
<id>1</id>
<name>Earth</name>
<radius>1.0</radius>
</planet>
just set the width of the td/column you want to be fixed and the rest will expand.
<td width="200"></td>
There are 2 different ways you can look for lowercase characters:
Use str.islower()
to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:
lowercase = [c for c in s if c.islower()]
You could use a regular expression:
import re
lc = re.compile('[a-z]+')
lowercase = lc.findall(s)
The first method returns a list of individual characters, the second returns a list of character groups:
>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']
A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update: ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
If you use an absolute path such as ("/index.jsp"
), there is no difference.
If you use relative path, you must use HttpServletRequest.getRequestDispatcher()
. ServletContext.getRequestDispatcher()
doesn't allow it.
For example, if you receive your request on http://example.com/myapp/subdir
,
RequestDispatcher dispatcher =
request.getRequestDispatcher("index.jsp");
dispatcher.forward( request, response );
Will forward the request to the page http://example.com/myapp/subdir/index.jsp
.
In any case, you can't forward request to a resource outside of the context.
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
This solution needs the jQuery's data method.
$._data($(".example").get(0), "events")
$._data()
is just accessing jQuery's data method. A more readable alternative could be jQuery._data()
.
Interesting point by this SO answer:
As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:
jQuery._data( elem, "events" );
elem should be an HTML Element, not a jQuery object, or selector.Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.
In older versions of jQuery, you might have to use the old method which is:
jQuery( elem ).data( "events" );
A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');
I had the same problem and i solved it by including jquery-3.1.1.min before including any js and it worked like a charm. Hope it helps.
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
Please correct the following line:
err = (TextView)findViewById(R.id.texto);
to:
err = (TextView)findViewById(R.id.err);
Leaving a reply (and an answer to the question title), For the future googlers...
You can use .length
to get the length of a string.
var x = 'Mozilla'; var empty = '';
console.log('Mozilla is ' + x.length + ' code units long');
/*"Mozilla is 7 code units long" */
console.log('The empty string has a length of ' + empty.length);
/*"The empty string has a length of 0" */
If you intend to get the length of a textarea
say id="txtarea"
then you can use the following code.
txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);
You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.
ATTENTION! If you only want to remove a file from your previous commit, and keep it on disk, read juzzlin's answer just above.
If this is your last commit and you want to completely delete the file from your local and the remote repository, you can:
git rm <file>
git commit --amend
The amend flag tells git to commit again, but "merge" (not in the sense of merging two branches) this commit with the last commit.
As stated in the comments, using git rm
here is like using the rm
command itself!
xampp in ubuntu
cd /opt/lampp/etc
vim php.ini
Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M
Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
sudo /opt/lampp/lampp restart
CGI is a mechanism whereby an external program is called by the web server in order to handle a request, with environment variables and standard input being used to feed the request data to the program. The exact language the external program is written in does not matter, although it is easier to write CGI programs in some languages versus others.
Since CGI scripts need execute permissions, httpd by default only allows CGI programs in the cgi-bin
directory to be run for (possibly now misguided) security purposes.
Most PHP scripts run in the web server process via mod_php
. This is not CGI.
CGI is slow since the program (and related interpreter) must be started up per request. Modern alternatives are embedded execution, used by mod_php, and long-running processes, used by FastCGI. A given language may have its own way of implementing those mechanisms, so be sure to ask around before resorting to CGI.
I know my answer is specific, but if one already has PHP and Symfony installed, it can be very handy to use Symfony's YAML parser.
For instance:
php -r "require '$SYMFONY_ROOT_PATH/vendor/autoload.php'; \
var_dump(\Symfony\Component\Yaml\Yaml::parse(file_get_contents('$YAML_FILE_PATH')));"
Here I simply used var_dump
to output the parsed array but of course you can do much more... :)
Use the PackageResourceViewer plugin installed via Package Control (as mentioned by MattDMo). This allows you to override the compressed resources by simply opening it in Sublime Text and saving the file. It automatically saves only the edited resources to %APPDATA%/Roaming/Sublime Text 3/Packages/ or ~/.config/sublime-text-3/Packages/.
Specific to the op, once the plugin is installed, execute the PackageResourceViewer: Open Resource
command. Then select JavaScript
followed by JavaScript.tmLanguage
. This will open an xml file in the editor. You can edit any of the language definitions and save the file. This will write an override copy of the JavaScript.tmLanguage file in the user directory.
The same method can be used to edit the language definition of any language in the system.
You can specify JsonSerializerSettings
for each JsonConvert
, and you can set a global default.
Single JsonConvert
with an overload:
// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);
// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
Global Setting with code in Application_Start()
in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
Jupyter Lab 1.0.4:
In the top menu, go to: Settings->Advanced Settings Editor->Keyboard Shortcuts
Paste this code in the User Preferences
window:
{
"shortcuts": [
{
"command": "runmenu:run-all",
"keys": [
"R",
"R"
],
"selector": "[data-jp-kernel-user]:focus"
}
]
}
user-preferences
window)This will be effective immediately. Here, two consecutive 'R' presses runs all cells (just like two '0' for kernel restart).
Notably, system defaults
has empty templates for all menu commands, including this code (search for run-all
). The selector
was copied from kernelmenu:restart
, to allow printing r
within cells. This system defaults
copy-paste can be generalized to any command.
If you have the files written under .gitignore, remove the files and run git pull again. That helped me out.
var results = from p in persons
group p by p.PersonID into g
select new { PersonID = g.Key, Cars = g.Select(m => m.car) };
I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.
Edit:
I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251
The cost of a connection(with epoll):
Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.
If you do have to do it this way, here's a few ways of doing it:
By far the easiest solution.
<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >
Might be OK if you're showing/hiding some complex markup.
<div ng-if="profileForm.$valid">
<input ng-click="updateMyProfile()" ... >
</div>
<div ng-if="!profileForm.$valid">
Sorry! We need all form fields properly filled out to continue.
</div>
(remember, there's no ng-else
...)
Communicating to the user where the button is (he won't look for it any longer), but explain why it can't be clicked.
<input ng-disabled="!profileForm.$valid" ng-click="updateMyProfile()" ... >
<div ng-if="!profileForm.$valid">
Sorry! We need all form fields properly filled out to continue.
</div>
You may also use the jQuery context parameter. Link to docs
Selector Context
By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function
Therefore you could also have:
success: function(data){
var oneval = $('#one',data).text();
var subval = $('#sub',data).text();
}
It's really late now but I made a quick script which works for Windows, Mac and Linux, simply by using each command line:
import os, platform
def close():
if platform.system() == "Windows":
print("Press any key to exit . . .")
os.system("pause>nul")
exit()
elif platform.system() == "Linux":
os.system("read -n1 -r -p \"Press any key to exit . . .\" key")
exit()
elif platform.system() == "Darwin":
print("Press any key to exit . . .")
os.system("read -n 1 -s -p \"\"")
exit()
else:
exit()
It uses only inbuilt functions, and should work for all three (although I've only tested Windows and Linux...).
I've found my own solution.
Download FreeDOS from here: http://chtaube.eu/computers/freedos/bootable-usb/
Then using my Counter.exe file (which basically generates a Counter.txt file and increments the number inside every time it's being called), I can assign the value of the number to a variable using:
Set /P Variable =< Counter.txt
Then, I can check if it has run 250 cycles by doing:
if %variable%==250 echo PASS
BTW, I still can't use Set /A since FreeDOS doesn't support this command, but at least it supports the Set /P command.
You forgot your class declaration:
public class MyClass {
...
An improved version of @Thomas K's answer:
is_any_thread_alive()
according to this gist, which can terminates the main()
automatically.Example codes:
import threading
def job1():
...
def job2():
...
def is_any_thread_alive(threads):
return True in [t.is_alive() for t in threads]
if __name__ == "__main__":
...
t1 = threading.Thread(target=job1,daemon=True)
t2 = threading.Thread(target=job2,daemon=True)
t1.start()
t2.start()
while is_any_thread_alive([t1,t2]):
time.sleep(0)
You are using a table variable i.e. you should declare the table. This is not a temporary table.
You create a temp table like so:
CREATE TABLE #customer
(
Name varchar(32) not null
)
You declare a table variable like so:
DECLARE @Customer TABLE
(
Name varchar(32) not null
)
Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables.
UPDATE:
Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.
Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):
CREATE PROCEDURE sproc_BuildTable
@TableName NVARCHAR(128)
,@Column1Name NVARCHAR(32)
,@Column1DataType NVARCHAR(32)
,@Column1Nullable NVARCHAR(32)
AS
DECLARE @SQLString NVARCHAR(MAX)
SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '
EXEC (@SQLString)
GO
This stored procedure can be executed like this:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'
There are some major problems with this type of stored procedure.
Its going to be difficult to cater for complex tables. Imagine the following table structure:
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [nvarchar](64) NOT NULL,
[CustomerSUrname] [nvarchar](64) NOT NULL,
[CustomerDateOfBirth] [datetime] NOT NULL,
[CustomerApprovedDiscount] [decimal](3, 2) NOT NULL,
[CustomerActive] [bit] NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount]
GO
This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.
Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?
Could you clarify why you need tables to be created dynamically?
UPDATE 2:
Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.
In this example I make the following assumptions:
Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).
Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.
First I would need a shop table to store all the information about the shop.
A simple shop table might look like this:
CREATE TABLE [dbo].[Shop](
[ShopID] [int] IDENTITY(1,1) NOT NULL,
[ShopName] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED
(
[ShopID] ASC
) WITH (
PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
Let's insert three shops into the database to use during our example. The following code will insert three shops:
INSERT INTO Shop
SELECT 'American Games R US'
UNION
SELECT 'Europe Gaming Experience'
UNION
SELECT 'Asian Games Emporium'
If you execute a SELECT * FROM Shop
you will probably see the following:
ShopID ShopName
1 American Games R US
2 Asian Games Emporium
3 Europe Gaming Experience
Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.
CREATE TABLE [dbo].[Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[ProductDescription] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Let's populate the products table with some products. Execute the following code to insert some products:
INSERT INTO Product
SELECT 'Wii'
UNION
SELECT 'PS3'
UNION
SELECT 'XBOX360'
If you execute SELECT * FROM Product
you will probably see the following:
ProductID ProductDescription
1 PS3
2 Wii
3 XBOX360
OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.
So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:
CREATE TABLE [dbo].[ShopProduct](
[ShopID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Price] [money] NOT NULL,
CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED
(
[ShopID] ASC,
[ProductID] ASC
)WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.
Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99
By executing the following code you would complete the mapping:
INSERT INTO ShopProduct VALUES(1,3,159.99)
Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.
To get this mapping done you would need to execute the following code:
INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99
INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99
INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99
At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:
SELECT Shop.*
, ShopProduct.*
, Product.*
FROM Shop
INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID
INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID
WHERE Shop.ShopID=3
You will probably see the following results:
ShopID ShopName ShopID ProductID Price ProductID ProductDescription
3 Europe Gaming Experience 3 1 259.99 1 PS3
3 Europe Gaming Experience 3 2 159.99 2 Wii
3 Europe Gaming Experience 3 3 199.99 3 XBOX360
Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.
You can execute the following query:
SELECT Shop.*
, ShopProduct.*
, Product.*
FROM Shop
INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID
INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID
WHERE Product.ProductID =3 -- You can also use Product.ProductDescription = 'XBOX360'
ORDER BY Price ASC
This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on.
You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship.
I hope this helps you in your travels with database design.
your question doesn't sound as if you even tried it yourself, so i shouldn't even think of answering, but: if a hidden div can't be printed with that one line:
$('SelectorToPrint').printElement();
simply change it to:
$('SelectorToPrint').show().printElement();
which should make it work in all cases.
for the rest, there's no solution. the plugin will open the print-dialog for you where the user has to choose his printer. you simply can't find out if a printer is attached with javascript (and you (almost) can't print without print-dialog - if you're thinking about that).
NOTE:
The
$.browser
object has been removed in version 1.9.x of jQuery making this library unsupported.
Use ->
when you have a pointer.
Use .
when you have structure (class).
When you want to point attribute that belongs to structure use .
:
structure.attribute
When you want to point to an attribute that has reference to memory by pointer use ->
:
pointer->method;
or same as:
(*pointer).method
That is the simple way of converting string into util date and sql date
String startDate="12-31-2014";
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:
HTML (note I'm assuming .cloumn
is a div
but it could be anything):
<div class="column" bf-width=100 >
<img src="..." />
</div>
jQuery:
// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());
And then in order to use that value in CSS:
.column:before {
content: attr(data-content) 'px';
/* ... */
}
This will grab the attribute value from .column
, and apply it on the before.
Sources: CSS attr (note the examples with before), jQuery attr.
I Have used this android:scaleType="fitXY"
code in Xml file.
Em dash style:
ul.emdash {
list-style-type: none;
list-style-position: inside;
text-indent: -1.25em;
}
ul.emdash > li:before {
content: "\2014\00A0"; /* em dash + space*/
}
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];
-(void)saveAction:(UIBarButtonItem *)sender{
//perform your action
}
I had the following code working perfect on my laptop:
& $msdeploy `
-source:package="$publishFile" `
-dest:auto,computerName="$server",includeAcls="False",UserName="$username",Password="$password",AuthType="$auth" `
-allowUntrusted `
-verb:sync `
-enableRule:DoNotDeleteRule `
-disableLink:AppPoolExtension `
-disableLink:ContentExtension `
-disableLink:CertificateExtension `
-skip:objectName=filePath,absolutePath="^(.*Web\.config|.*Environment\.config)$" `
-setParam:name=`"IIS Web Application Name`",value="$appName"
Then when I tried to run that directly on one server I started getting those errors "Unrecognized argument ...etc.... All arguments must begin with "-". "
After trying all possible workarounds (no success), I found out that Powershell on the server (Windows 2008 R2) was version 3.0, while my laptop has 5.0. (you can use "$PSVersionTable" to see version).
After upgrading Powershell to latest version it started working again.
Old post. I ended up setting media queries and using max-width: YYpx;
and width:auto;
for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md
screen), the modal will scale down to 740px (excluding padding for the .modal-body
, if applied)
<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<div class="modal-body"></div>
</div>
</div>
</div>
Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss
file that _bootstrap.scss
imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss
.
It is also important to note that the original bootstrap styles for .modal-dialog
is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;
, hence why I overrode it w/ width: auto;
.
@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
.modal-dialog {
max-width: 600px;
width: auto;
}
}
@media (min-width: $screen-md-min) { // this is the 992px breakpoint
.modal-dialog {
max-width: 800px;
}
}
Example below of modal being responsive with an image.
Wrap each individual condition in parentheses, and then use the &
operator to combine the conditions:
df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']
You can fill the non-matching rows by just using ~
(the "not" operator) to invert the match:
df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''
You need to use &
and ~
rather than and
and not
because the &
and ~
operators work element-by-element.
The final result:
df
Out[8]:
one two three que
0 10 1.2 4.2 10
1 15 70 0.03
2 8 5 0