1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
This can be simply done like this.
created() {
var scripts = [
"https://cloudfront.net/js/jquery-3.4.1.min.js",
"js/local.js"
];
scripts.forEach(script => {
let tag = document.createElement("script");
tag.setAttribute("src", script);
document.head.appendChild(tag);
});
}
I found it very useful, since the Exceptions are not documented, to list all exceptions to the screen for this package. Here is the code I used to do it:
import botocore.exceptions
def listexns(mod):
#module = __import__(mod)
exns = []
for name in botocore.exceptions.__dict__:
if (isinstance(botocore.exceptions.__dict__[name], Exception) or
name.endswith('Error')):
exns.append(name)
for name in exns:
print('%s.%s is an exception type' % (str(mod), name))
return
if __name__ == '__main__':
import sys
if len(sys.argv) <= 1:
print('Give me a module name on the $PYTHONPATH!')
print('Looking for exception types in module: %s' % sys.argv[1])
listexns(sys.argv[1])
Which results in:
Looking for exception types in module: boto3
boto3.BotoCoreError is an exception type
boto3.DataNotFoundError is an exception type
boto3.UnknownServiceError is an exception type
boto3.ApiVersionNotFoundError is an exception type
boto3.HTTPClientError is an exception type
boto3.ConnectionError is an exception type
boto3.EndpointConnectionError is an exception type
boto3.SSLError is an exception type
boto3.ConnectionClosedError is an exception type
boto3.ReadTimeoutError is an exception type
boto3.ConnectTimeoutError is an exception type
boto3.ProxyConnectionError is an exception type
boto3.NoCredentialsError is an exception type
boto3.PartialCredentialsError is an exception type
boto3.CredentialRetrievalError is an exception type
boto3.UnknownSignatureVersionError is an exception type
boto3.ServiceNotInRegionError is an exception type
boto3.BaseEndpointResolverError is an exception type
boto3.NoRegionError is an exception type
boto3.UnknownEndpointError is an exception type
boto3.ConfigParseError is an exception type
boto3.MissingParametersError is an exception type
boto3.ValidationError is an exception type
boto3.ParamValidationError is an exception type
boto3.UnknownKeyError is an exception type
boto3.RangeError is an exception type
boto3.UnknownParameterError is an exception type
boto3.AliasConflictParameterError is an exception type
boto3.PaginationError is an exception type
boto3.OperationNotPageableError is an exception type
boto3.ChecksumError is an exception type
boto3.UnseekableStreamError is an exception type
boto3.WaiterError is an exception type
boto3.IncompleteReadError is an exception type
boto3.InvalidExpressionError is an exception type
boto3.UnknownCredentialError is an exception type
boto3.WaiterConfigError is an exception type
boto3.UnknownClientMethodError is an exception type
boto3.UnsupportedSignatureVersionError is an exception type
boto3.ClientError is an exception type
boto3.EventStreamError is an exception type
boto3.InvalidDNSNameError is an exception type
boto3.InvalidS3AddressingStyleError is an exception type
boto3.InvalidRetryConfigurationError is an exception type
boto3.InvalidMaxRetryAttemptsError is an exception type
boto3.StubResponseError is an exception type
boto3.StubAssertionError is an exception type
boto3.UnStubbedResponseError is an exception type
boto3.InvalidConfigError is an exception type
boto3.InfiniteLoopConfigError is an exception type
boto3.RefreshWithMFAUnsupportedError is an exception type
boto3.MD5UnavailableError is an exception type
boto3.MetadataRetrievalError is an exception type
boto3.UndefinedModelAttributeError is an exception type
boto3.MissingServiceIdError is an exception type
In case of an associative array or numbered array where you do not want to change the array keys:
$firstItem = array('foo' => 'bar');
$arr = $firstItem + $arr;
array_merge
does not work as it always reindexes the array.
it also can be a great idea using concat for EL + MAP + JSON problem like in this example :
#{myMap[''.concat(myid)].content}
Given a list:
var list = new List<Child>()
{
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};
The query would look like:
var newList = list
.GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
.Select(y => new ConsolidatedChild()
{
FavoriteColor = y.Key.FavoriteColor,
Friend = y.Key.Friend,
School = y.Key.School,
Children = y.ToList()
}
);
Test code:
foreach(var item in newList)
{
Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
foreach(var child in item.Children)
{
Console.WriteLine("\t Name: {0}", child.Name);
}
}
Result:
School: School1 FavouriteColor: blue Friend: Bob
Name: John
Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
Name: Bob
I couldn't ever find an answer that really satisfied the original question, so I put together a simple free service (PostMail) that allows you to make a standard HTTP POST request to send an email. When you sign up, it provides you with code that you can copy & paste into your website. In this case, you can simply use a form post:
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message"></textarea>
<!-- replace value with your access token -->
<input type="hidden" name="access_token" value="{your access token}" />
<input type="hidden" name="success_url"
value=".?message=Email+Successfully+Sent%21&isError=0" />
<input type="hidden" name="error_url"
value=".?message=Email+could+not+be+sent.&isError=1" />
<input id="submit_form" type="submit" value="Send" />
</form>
Again, in full disclosure, I created this service because I could not find a suitable answer.
When one of my VB.NET classes has all shared members I either convert it to a Module with a matching (or otherwise appropriate) namespace or I make the class not inheritable and not constructable:
Public NotInheritable Class MyClass1
Private Sub New()
'Contains only shared members.
'Private constructor means the class cannot be instantiated.
End Sub
End Class
I had to modify Lars' answer a bit, as an orphaned \
ended up in the regex, to only compare the actual host (not paying attention to the protocol or port) and I wanted to support localhost
domain besides my production domain. Thus I changed the $allowed
parameter to be an array.
function getCORSHeaderOrigin($allowed, $input)
{
if ($allowed == '*') {
return '*';
}
if (!is_array($allowed)) {
$allowed = array($allowed);
}
foreach ($allowed as &$value) {
$value = preg_quote($value, '/');
if (($wildcardPos = strpos($value, '\*')) !== false) {
$value = str_replace('\*', '(.*)', $value);
}
}
$regexp = '/^(' . implode('|', $allowed) . ')$/';
$inputHost = parse_url($input, PHP_URL_HOST);
if ($inputHost === null || !preg_match($regexp, $inputHost, $matches)) {
return 'none';
}
return $input;
}
Usage as follows:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: " . getCORSHeaderOrigin(array("*.myproduction.com", "localhost"), $_SERVER['HTTP_ORIGIN']));
}
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);
This code works for every date format.
You can change the order of replacement variables such $3-$1-$2 due to your old date format.
If we want to apply the same functionality and features to more than one selectors then we use multiple selector options. I think we can say this feature is used like reusability. write a jquery function and just add multiple selectors in which we want the same features.
Kindly take a look in below example:
$( "div, span, .paragraph, #paraId" ).css( {"font-family": "tahoma", "background": "red"} );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>Div element</div>_x000D_
<p class="paragraph">Paragraph with class selector</p>_x000D_
<p id="paraId">Paragraph with id selector</p>_x000D_
<span>Span element</span>
_x000D_
I hope it will help you. Namaste
I ran this in the command prompt(have windows 7 os): JAVA_HOME=C:\Program Files\Android\Android Studio\jre
where what its = to is the path to that jre folder, so anyone's can be different.
// WPF
// Defined Color
button1.Background = Brushes.Green;
// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
I am using Ansible 1.9.4 and this is what worked for me -
- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.
Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
Nothing to mess up buddy!!
If we have a positive valued functions f(n) and g(n) takes a positive valued argument n then ?(g(n)) defined as {f(n):there exist constants c1,c2 and n1 for all n>=n1}
where c1 g(n)<=f(n)<=c2 g(n)
c1=5 and c2=8 and n1=1
Among all the notations ,? notation gives the best intuition about the rate of growth of function because it gives us a tight bound unlike big-oh and big -omega which gives the upper and lower bounds respectively.
? tells us that g(n) is as close as f(n),rate of growth of g(n) is as close to the rate of growth of f(n) as possible.
Is the standard procedure not working?
git stash save
git branch xxx HEAD
git checkout xxx
git stash pop
Shorter:
git stash
git checkout -b xxx
git stash pop
Not a valid floating-point value (e.g. the result of division by zero)
codepen Is perhaps a helpful example.
<div class="social-icons">
<a class="social-icon social-icon--codepen">
<i class="fa fa-codepen"></i>
<div class="tooltip">Codepen</div>
</div>
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
/* Color Variables */
$color-codepen: #000;
/* Social Icon Mixin */
@mixin social-icon($color) {
background: $color;
background: linear-gradient(tint($color, 5%), shade($color, 5%));
border-bottom: 1px solid shade($color, 20%);
color: tint($color, 50%);
&:hover {
color: tint($color, 80%);
text-shadow: 0px 1px 0px shade($color, 20%);
}
.tooltip {
background: $color;
background: linear-gradient(tint($color, 15%), $color);
color: tint($color, 80%);
&:after {
border-top-color: $color;
}
}
}
/* Social Icons */
.social-icons {
display: flex;
}
.social-icon {
display: flex;
align-items: center;
justify-content: center;
position: relative;
width: 80px;
height: 80px;
margin: 0 0.5rem;
border-radius: 50%;
cursor: pointer;
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
font-size: 2.5rem;
text-decoration: none;
text-shadow: 0 1px 0 rgba(0,0,0,0.2);
transition: all 0.15s ease;
&:hover {
color: #fff;
.tooltip {
visibility: visible;
opacity: 1;
transform: translate(-50%, -150%);
}
}
&:active {
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5) inset;
}
&--codepen { @include social-icon($color-codepen); }
i {
position: relative;
top: 1px;
}
}
/* Tooltips */
.tooltip {
display: block;
position: absolute;
top: 0;
left: 50%;
padding: 0.8rem 1rem;
border-radius: 3px;
font-size: 0.8rem;
font-weight: bold;
opacity: 0;
pointer-events: none;
text-transform: uppercase;
transform: translate(-50%, -100%);
transition: all 0.3s ease;
z-index: 1;
&:after {
display: block;
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 0;
content: "";
border: solid;
border-width: 10px 10px 0 10px;
border-color: transparent;
transform: translate(-50%, 100%);
}
}
The most problems appear when you want to add new host to dynamic inventory (via add_host module) in playbook. I don't want to disable fingerprint host checking permanently so solutions like disabling it in a global config file are not ok for me. Exporting var like ANSIBLE_HOST_KEY_CHECKING
before running playbook is another thing to do before running that need to be remembered.
It's better to add local config file in the same dir where playbook is. Create file named ansible.cfg
and paste following text:
[defaults]
host_key_checking = False
No need to remember to add something in env vars or add to ansible-playbook
options. It's easy to put this file to ansible git repo.
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
In Angular 2 you can subscribe
(Rx event) to a Router instance.
So you can do things like
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
Edit (since rc.1)
class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
Edit 2 (since 2.0.0)
see also : Router.events doc
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
$_SERVER['SERVER_NAME'] is based on your web servers configuration. $_SERVER['HTTP_HOST'] is based on the request from the client.
You push your local repository to the remote repository using the git push
command after first establishing a relationship between the two with the git remote add [alias] [url]
command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:
git remote add origin [email protected]:username/reponame.git
Unless you started by running git clone
against the remote repository, in which case this step has been done for you already.
And after that, you'll type:
git push origin master
After your first push, you can simply type:
git push
when you want to update the remote repository in the future.
WebView browser = (WebView) findViewById(R.id.webview);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
browser.getSettings().setMinimumFontSize(40);
This works great for me since the text size has been set to really small by .setLoadWithOverViewMode and .setUseWideViewPort.
Why are you including the getClassLoader step? If you say "this.getClass().getResource()" you should be getting resources relative to the calling class. I've never used ClassLoader.getResource(), though from a quick look at the Java Docs it sounds like that will get you the first resource of that name found in any current classpath.
Another Javascript Solution
for(var i=0,keys = Object.keys(obj),len=keys.length;i<len;i++){
if(typeof obj[keys[i]] === 'undefined'){
delete obj[keys[i]];
}
}
No additional hasOwnProperty
check is required as Object.keys
does not look up the prototype chain and returns only the properties of obj
.
I use the below mentioned process to convert equations to markdown. This works very well for me. Its very simple!!
Let's say, I want to represent matrix multiplication equation
Get the script for your formulae from here - https://csrgxtu.github.io/2015/03/20/Writing-Mathematic-Fomulars-in-Markdown/
My example: I wanted to represent Z(i,j)=X(i,k) * Y(k, j); k=1 to n
into a summation formulae.
Referencing the website, the script needed was => Z_i_j=\sum_{k=1}^{10} X_i_k * Y_k_j
Use URL encoder - https://www.urlencoder.org/ to convert the script to a valid url
My example:
Use this website to generate the image by copy-pasting the output from Step 2 in the "eq" request parameter - http://www.sciweavers.org/tex2img.php?eq=<b><i>paste-output-here</i></b>&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=
- My example:
http://www.sciweavers.org/tex2img.php?eq=Z_i_j=\sum_{k=1}^{10}%20X_i_k%20*%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=
Reference image using markdown syntax - ![alt text](enter url here)
- Copy this in your markdown and you are good to go:
![Z(i,j)=X(i,k) * Y(k, j); k=1 to n](http://www.sciweavers.org/tex2img.php?eq=Z_i_j%3D%5Csum_%7Bi%3D1%7D%5E%7B10%7D%20X_i_k%20%2A%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)
You get that error because you don't have the public key of the person who signed the message.
gpg
should have given you a message containing the ID of the key that was used to sign it. Obtain the public key from the person who encrypted the file and import it into your keyring (gpg2 --import key.asc
); you should be able to verify the signature after that.
If the sender submitted its public key to a keyserver (for instance, https://pgp.mit.edu/), then you may be able to import the key directly from the keyserver:
gpg2 --keyserver https://pgp.mit.edu/ --search-keys <sender_name_or_address>
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
I was able to import the module within the function (only) that would require the objects from this module:
def my_func():
import Foo
foo_instance = Foo()
Always use either String.valueOf(number)
or Integer.toString(number)
.
Using "" + number is an overhead and does the following:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();
And how about this:
public static void watchYoutubeVideo(Context context, String id){
Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=" + id));
try {
context.startActivity(appIntent);
} catch (ActivityNotFoundException ex) {
context.startActivity(webIntent);
}
}
Note: Beware when you are using this method, YouTube may suspend your channel due to spam, this happened two times with me
Yup, as everyone's saying, line-height
is the thing.
Any font you are using, a mid-height character (such as a or ¦, not going through the upper or lower) should go with the same height-length at line-height: 0.6
to 0.65
.
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div style="line-height: 0.6; font-family: 'Fira Code', monospace, sans-serif">_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
<strong>BUT</strong>_x000D_
<br>_x000D_
<br>_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
ddd<br>_x000D_
ƒƒƒ<br>_x000D_
ggg_x000D_
</div>
_x000D_
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
I believe
rgba( 0, 0, 0, 0.8 )
is equivalent in shade with #333
.
Live demo: http://jsfiddle.net/8MVC5/1/
Setting background size does not help, the following solution worked for me:
.class {
background-image: url(blablabla.jpg);
/* Add this */
height: auto;
}
It basically crops the image and makes it fit in, background-size: contain/cover
still didn't make it fit.
Might be a bit odd or bad practice but this is one way of going about it.
(arg1, arg2, arg3) = (1, 2, 3)
if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
print('Example.')
Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.
You can use templates.
template <typename T> const char* typeof(T&) { return "unknown"; } // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(float&) { return "float"; }
In the example above, when the type is not matched it will print "unknown".
str_split
can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won't need to split your string into a "new" array.
Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.
The value of the length property must be greater than or equal to name atribute length, else throwing an error.
Works
@Column(name = "typ e", length = 4, unique = true)
private String type;
Not works, type.length: 4 != length property: 3
@Column(name = "type", length = 3, unique = true)
private String type;
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
In my case it is required to calculate the complete month from the start date to the day prior to this day in the next month or from start to end of month.
Ex: from 1/1/2018 to 31/1/2018 is a complete month
Ex2: from 5/1/2018 to 4/2/2018 is a complete month
so based on this here is my solution:
public static DateTime GetMonthEnd(DateTime StartDate, int MonthsCount = 1)
{
return StartDate.AddMonths(MonthsCount).AddDays(-1);
}
public static Tuple<int, int> CalcPeriod(DateTime StartDate, DateTime EndDate)
{
int MonthsCount = 0;
Tuple<int, int> Period;
while (true)
{
if (GetMonthEnd(StartDate) > EndDate)
break;
else
{
MonthsCount += 1;
StartDate = StartDate.AddMonths(1);
}
}
int RemainingDays = (EndDate - StartDate).Days + 1;
Period = new Tuple<int, int>(MonthsCount, RemainingDays);
return Period;
}
Usage:
Tuple<int, int> Period = CalcPeriod(FromDate, ToDate);
Note: in my case it was required to calculate the remaining days after the complete months so if it's not your case you could ignore the days result or even you could change the method return from tuple to integer.
One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.
template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};
template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};
template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
typedef FooImpl<T, boost::is_integer<T> > inherited;
// you will need to use "inherited::" if you want to name any of the
// members of those inherited classes.
};
The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.
Ex:
template<class T, bool condition> class Goo;
// repeat pattern above.
template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
typedef Goo<T, boost::test<T> > inherited:
// etc. etc.
};
That worked for me:
input:
[complex(a,b) for a,b in zip([1,2,3],[1,2,3])]
output:
[(1+4j), (2+5j), (3+6j)]
A simple example would be
DECLARE @number INTEGER
DECLARE @length INTEGER
DECLARE @char NVARCHAR(10)
SET @number = 1
SET @length = 5
SET @char = '0'
SELECT FORMAT(@number, replicate(@char, @length))
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
except:
accepts all exceptions, whereas
except Exception as e:
only accepts exceptions that you're meant to catch.
Here's an example of one that you're not meant to catch:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
Here's a quick list:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
except BaseException:
to point out that you know what you're doing.
All exceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception
.
A non-jQuery solution is much like a jQuery solution:
document.querySelector('#myinput').getAttribute('type') === 'checkbox'
If you have InteliJ Idea Community 2018.2 the steps are as fallows:
Restart your IDE and try it.
I know what you're going to say, the guys before me wrote the same thing. But I got confused using the steps above this post, and I wanted to write a dumb down version for people who have the latest version of the IDE.
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
After spending hours on this issue found solution here
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule
]
})
It sounds like you currently have 3 copies of the entire file in memory: the byte array, the string, and the array of the lines.
Instead of reading the bytes into a byte array and then converting to characters using new String()
it would be better to use an InputStreamReader, which will convert to characters incrementally, rather than all up-front.
Also, instead of using String.split("\n") to get the individual lines, you should read one line at a time. You can use the readLine()
method in BufferedReader
.
Try something like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
try {
while (true) {
String line = reader.readLine();
if (line == null) break;
String[] fields = line.split(",");
// process fields here
}
} finally {
reader.close();
}
Some interesting excerpts from the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from/etc/bash.bashrc
and~/.bashrc
, if these files exist. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of/etc/bash.bashrc
and~/.bashrc
.
So have a look at /etc/profile
or /etc/bash.bashrc
, these files are the right places for global settings. Put something like this in them to set up an environement variable:
export MY_VAR=xxx
If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.
A nested dict is a dictionary within a dictionary. A very simple thing.
>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}
You can also use a defaultdict
from the collections
package to facilitate creating nested dictionaries.
>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d) # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}
You can populate that however you want.
I would recommend in your code something like the following:
d = {} # can use defaultdict(dict) instead
for row in file_map:
# derive row key from something
# when using defaultdict, we can skip the next step creating a dictionary on row_key
d[row_key] = {}
for idx, col in enumerate(row):
d[row_key][idx] = col
According to your comment:
may be above code is confusing the question. My problem in nutshell: I have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has these columns. i is kind of key columns for these csvs'. j k l column is empty in a.csv but populated in b.csv. I want to map values of j k l columns using 'i` as key column from b.csv to a.csv file
My suggestion would be something like this (without using defaultdict):
a_file = "path/to/a.csv"
b_file = "path/to/b.csv"
# read from file a.csv
with open(a_file) as f:
# skip headers
f.next()
# get first colum as keys
keys = (line.split(',')[0] for line in f)
# create empty dictionary:
d = {}
# read from file b.csv
with open(b_file) as f:
# gather headers except first key header
headers = f.next().split(',')[1:]
# iterate lines
for line in f:
# gather the colums
cols = line.strip().split(',')
# check to make sure this key should be mapped.
if cols[0] not in keys:
continue
# add key to dict
d[cols[0]] = dict(
# inner keys are the header names, values are columns
(headers[idx], v) for idx, v in enumerate(cols[1:]))
Please note though, that for parsing csv files there is a csv module.
You don't always want to discard a race condition. If you have a flag which can be read and written by multiple threads, and this flag is set to 'done' by one thread so that other thread stop processing when flag is set to 'done', you don't want that "race condition" to be eliminated. In fact, this one can be referred to as a benign race condition.
However, using a tool for detection of race condition, it will be spotted as a harmful race condition.
More details on race condition here, http://msdn.microsoft.com/en-us/magazine/cc546569.aspx.
For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...
replace this <a onClick={props.signOut()}>Log Out</a>
with this <a onClick={props.signOut}>Log Out</a>
... !
After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE. I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions. Based upon that information, I then created a small Action routine which determines why the trigger has been activated. This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger. In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem. (i.e. were both triggers updated properly for the necessary common data algorithm fix?)
To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.
CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;
--
-- Variables Needed for this Trigger
--
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
--
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
BEGIN
SET @Action = 'D' -- Set Action to 'D'eleted.
SELECT @Count = COUNT(*) FROM INSERTED
IF @Count > 0
SET @Action = 'U' -- Set Action to 'U'pdated.
END
if @Action = 'D'
-- This is a DELETE Record Action
--
BEGIN
SELECT @PACKLIST_ID =[PACKLIST_ID]
,@LINE_NO = [LINE_NO]
FROM DELETED
DELETE [dbo].[MyDataTable]
WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
END
Else
BEGIN
--
-- Table INSERTED is common to both the INSERT, UPDATE trigger
--
SELECT @PACKLIST_ID =[PACKLIST_ID]
,@LINE_NO = [LINE_NO]
,@SHIPPED_QTY =[SHIPPED_QTY]
,@CUST_ORDER_ID = [CUST_ORDER_ID]
FROM INSERTED
if @Action = 'I'
-- This is an Insert Record Action
--
BEGIN
INSERT INTO [MyChildTable]
(([PACKLIST_ID]
,[LINE_NO]
,[STATUS]
VALUES
(@PACKLIST_ID
,@LINE_NO
,'New Record'
)
END
else
-- This is an Update Record Action
--
BEGIN
UPDATE [MyChildTable]
SET [PACKLIST_ID] = @PACKLIST_ID
,[LINE_NO] = @LINE_NO
,[STATUS]='Update Record'
WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
END
END
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
Drop the parentheses and commas:
myBackupFunction ".." "..." "xx"
And the function should look like this:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
Sadly there is no overload in PHP as it is done in C#. But i have a little trick. I declare arguments with default null values and check them in a function. That way my function can do different things depending on arguments. Below is simple example:
public function query($queryString, $class = null) //second arg. is optional
{
$query = $this->dbLink->prepare($queryString);
$query->execute();
//if there is second argument method does different thing
if (!is_null($class)) {
$query->setFetchMode(PDO::FETCH_CLASS, $class);
}
return $query->fetchAll();
}
//This loads rows in to array of class
$Result = $this->query($queryString, "SomeClass");
//This loads rows as standard arrays
$Result = $this->query($queryString);
One more option in simple way
Map<String,Choice> map = new HashMap<>();
choices.forEach(e->map.put(e.getName(),e));
To get started, you should download the source code from Github, by following the instructions here (you'll need Bazel and a recent version of GCC).
The C++ API (and the backend of the system) is in tensorflow/core
. Right now, only the C++ Session interface, and the C API are being supported. You can use either of these to execute TensorFlow graphs that have been built using the Python API and serialized to a GraphDef
protocol buffer. There is also an experimental feature for building graphs in C++, but this is currently not quite as full-featured as the Python API (e.g. no support for auto-differentiation at present). You can see an example program that builds a small graph in C++ here.
The second part of the C++ API is the API for adding a new OpKernel
, which is the class containing implementations of numerical kernels for CPU and GPU. There are numerous examples of how to build these in tensorflow/core/kernels
, as well as a tutorial for adding a new op in C++.
Works for every browser.
<button type="button" onClick="Refresh()">Close</button>
<script>
function Refresh() {
window.parent.location = window.parent.location.href;
}
</script>
I think you could just use class "col-md-12" it has required left and right paddings and 100% width. Looks like this is a good replacement for container-fluid from 2nd bootstrap.
The solution using flexbox without justify-content: space-between
.
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title {
display: flex;
}
span:first-of-type {
flex: 1;
}
When we use flex:1
on the first <span>
, it takes up the entire remaining space and moves the second <span>
to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/
Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between
and flexbox with flex:1
on the first <span>
.
There seems to be a really easy solution when dealing with data type issues.
Basically, at the end of Excel connection string, add ;IMEX=1;"
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";
This will resolve data type issues such as columns where values are mixed with text and numbers.
To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.
I wrote a short convenience function for posting JSON.
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
An updated answer here as of 2017, should anyone need it, is that onhashchange
is well supported in all major browsers. See caniuse for details. To use it with jQuery no plugin is needed:
$( window ).on( 'hashchange', function( e ) {
console.log( 'hash changed' );
} );
Occasionally I come across legacy systems where hashbang URL's are still used and this is helpful. If you're building something new and using hash links I highly suggest you consider using the HTML5 pushState API instead.
Followings gives dimensions as well as channels:
import numpy as np
from PIL import Image
with Image.open(filepath) as img:
shape = np.array(img).shape
Breaking out of Array#forEach is not possible. (You can inspect the source code that implements it in Firefox on the linked page, to confirm this.)
Instead you should use a normal for
loop:
function recurs(comment) {
for (var i = 0; i < comment.comments.length; ++i) {
var subComment = comment.comments[i];
recurs(subComment);
if (...) {
break;
}
}
}
(or, if you want to be a little more clever about it and comment.comments[i]
is always an object:)
function recurs(comment) {
for (var i = 0, subComment; subComment = comment.comments[i]; ++i) {
recurs(subComment);
if (...) {
break;
}
}
}
I couldn't get the first method to work, and I know this is an old topic, but this is what I ended up doing for a solution:
=IF(ISNA(MATCH(A1,B:B,0)),"Not Matched", A1)
Basically, MATCH A1 to Column B exactly (the 0 stands for match exactly to a value in Column B). ISNA tests for #N/A response which match will return if the no match is found. Finally, if ISNA is true, write "Not Matched" to the selected cell, otherwise write the contents of the matched cell.
fatal error: unexpectedly found nil while unwrapping an Optional value
:) hopes it will help for some struggled people .
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
Try this:
private void NewNumber()
{
Random a = new Random(Guid.newGuid().GetHashCode());
MyNumber = a.Next(0, 10);
}
Some Explnations:
Guid
: base on here : Represents a globally unique identifier (GUID)
Guid.newGuid()
produces a unique identifier like "936DA01F-9ABD-4d9d-80C7-02AF85C822A8"
and it will be unique in all over the universe base on here
Hash code here produce a unique integer from our unique identifier
so Guid.newGuid().GetHashCode()
gives us a unique number and the random class will produce real random numbers throw this
Sample: https://rextester.com/ODOXS63244
generated ten random numbers with this approach with result of:
-1541116401
7
-1936409663
3
-804754459
8
1403945863
3
1287118327
1
2112146189
1
1461188435
9
-752742620
4
-175247185
4
1666734552
7
we got two 1
s next to each other, but the hash codes do not same.
I just made this for my app :
public static Date getDatePart(Date dateTime) {
TimeZone tz = TimeZone.getDefault();
long rawOffset=tz.getRawOffset();
long dst=(tz.inDaylightTime(dateTime)?tz.getDSTSavings():0);
long dt=dateTime.getTime()+rawOffset+dst; // add offseet and dst to dateTime
long modDt=dt % (60*60*24*1000) ;
return new Date( dt
- modDt // substract the rest of the division by a day in milliseconds
- rawOffset // substract the time offset (Paris = GMT +1h for example)
- dst // If dayLight, substract hours (Paris = +1h in dayLight)
);
}
Android API level 1, no external library. It respects daylight and default timeZone. No String manipulation so I think this way is more CPU efficient than yours but I haven't made any tests.
class _YourClassState extends State<YourClass> {
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.text = 'Your message';
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: TextFormField(
controller: _controller,
decoration: InputDecoration(labelText: 'Send message...'),
),
);
}
}
As a quick and very scoped solution:
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
TLDR
~ is what you want most of the time, it references past commits to the current branch
^ references parents (git-merge creates a 2nd parent or more)
A~ is always the same as A^
A~~ is always the same as A^^, and so on
A~2 is not the same as A^2 however,
because ~2 is shorthand for ~~
while ^2 is not shorthand for anything, it means the 2nd parent
Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:
/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i
[1] The question is about checking variables, so we should include the user-unfriendly form as well.
My problem was in my XML lyout I have an android:animateLayoutChanges set to true and I've called notifyDataSetChanged() on the RecyclerView's adapter in the Java code.
So, I've just removed android:animateLayoutChanges from my layout and that resloved my problem.
The problem is that your ui
property uses a forward declaration of class Ui::MainWindowClass
, hence the "incomplete type" error.
Including the header file in which this class is declared will fix the problem.
EDIT
Based on your comment, the following code:
namespace Ui
{
class MainWindowClass;
}
does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.
But the class has to be defined somewhere.
Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.
So either you actually want an incomplete type, and then you should declare your ui
member as a pointer:
namespace Ui
{
// Forward declaration - Class will have to exist at link time
class MainWindowClass;
}
class MainWindow : public QMainWindow
{
private:
// Member needs to be a pointer, as it's an incomplete type
Ui::MainWindowClass * ui;
};
Or you want a statically allocated instance of Ui::MainWindowClass
, and then it needs to be declared.
You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:
namespace Ui
{
// Real class declaration - May/Should be in a specific header file
class MainWindowClass
{};
}
class MainWindow : public QMainWindow
{
private:
// Member can be statically allocated, as the type is complete
Ui::MainWindowClass ui;
};
will also work.
Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).
The design of C# suggests that inline initialization is preferred, or it wouldn't be in the language. Any time you can avoid a cross-reference between different places in the code, you're generally better off.
There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for Constructor Design say this:
? CONSIDER initializing static fields inline rather than explicitly using static constructors, because the runtime is able to optimize the performance of types that don’t have an explicitly defined static constructor.
"Consider" in this context means to do so unless there's a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline.
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
Use read_table(filepath)
. The default separator is tab
Select all text in the document and press Ctrl + E + D.
You don't need to configure anything. Just make sure that the requests map to your PHP file and use requests with path info. For example, if you have in the root a file named handler.php
with this content:
<?php
var_dump($_SERVER['REQUEST_METHOD']);
var_dump($_SERVER['REQUEST_URI']);
var_dump($_SERVER['PATH_INFO']);
if (($stream = fopen('php://input', "r")) !== FALSE)
var_dump(stream_get_contents($stream));
The following HTTP request would work:
Established connection with 127.0.0.1 on port 81
PUT /handler.php/bla/foo HTTP/1.1
Host: localhost:81
Content-length: 5
boo
HTTP/1.1 200 OK
Date: Sat, 29 May 2010 16:00:20 GMT
Server: Apache/2.2.13 (Win32) PHP/5.3.0
X-Powered-By: PHP/5.3.0
Content-Length: 89
Content-Type: text/html
string(3) "PUT"
string(20) "/handler.php/bla/foo"
string(8) "/bla/foo"
string(5) "boo
"
Connection closed remotely.
You can hide the "php" extension with MultiViews or you can make URLs completely logical with mod_rewrite.
See also the documentation for the AcceptPathInfo directive and this question on how to make PHP not parse POST data when enctype is multipart/form-data
.
jQuery.offset
needs to be combined with scrollTop
and scrollLeft
as shown in this diagram:
Demo:
function getViewportOffset($e) {_x000D_
var $window = $(window),_x000D_
scrollLeft = $window.scrollLeft(),_x000D_
scrollTop = $window.scrollTop(),_x000D_
offset = $e.offset(),_x000D_
rect1 = { x1: scrollLeft, y1: scrollTop, x2: scrollLeft + $window.width(), y2: scrollTop + $window.height() },_x000D_
rect2 = { x1: offset.left, y1: offset.top, x2: offset.left + $e.width(), y2: offset.top + $e.height() };_x000D_
return {_x000D_
left: offset.left - scrollLeft,_x000D_
top: offset.top - scrollTop,_x000D_
insideViewport: rect1.x1 < rect2.x2 && rect1.x2 > rect2.x1 && rect1.y1 < rect2.y2 && rect1.y2 > rect2.y1_x000D_
};_x000D_
}_x000D_
$(window).on("load scroll resize", function() {_x000D_
var viewportOffset = getViewportOffset($("#element"));_x000D_
$("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top + ", insideViewport: " + viewportOffset.insideViewport);_x000D_
});
_x000D_
body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }_x000D_
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }_x000D_
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- scroll right and bottom to locate the blue square -->_x000D_
<div id="element"></div>_x000D_
<div id="log"></div>
_x000D_
You would need to always consider the state of all checkboxes!
You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.
So you always need to check all of them:
<script type="text/javascript">
<!--
function showMe (it, box) {
// consider all checkboxes with same name
var checked = amountChecked(box.name);
var vis = (checked >= 3) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
function amountChecked(name) {
var all = document.getElementsByName(name);
// count checked
var result = 0;
all.forEach(function(el) {
if (el.checked) result++;
});
return result;
}
//-->
</script>
Angular 2 or 4:
There's no more ng-repeat, it's *ngFor now in recent Angular versions!
<table style="padding: 20px; width: 60%;">
<tr>
<th align="left">id</th>
<th align="left">status</th>
<th align="left">name</th>
</tr>
<tr *ngFor="let item of myJSONArray">
<td>{{item.id}}</td>
<td>{{item.status}}</td>
<td>{{item.name}}</td>
</tr>
</table>
Used this simple JSON:
[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]
This is a classic difficulty in LaTeX.
The problem is how to do layout with floats (figures and tables, an similar objects) and footnotes. In particular, it is hard to pick a place for a float with certainty that making room for the associated footnotes won't cause trouble. So the standard tabular
and figure
environments don't even try.
What can you do:
\footnotesize
for the size). You also have to manage the symbols or number yourself with \footnotemark
. Simple, but not very attractive, and the footnote does not appear at the bottom of the page.tabularx
, longtable
, threeparttable[x]
(kudos to Joseph) or ctable
which support this behavior.[h!]
(or [H]
with the float package) to control where the float will appear, and \footnotetext
on the same page to put the footnote where you want it. Again, use \footnotemark
to install the symbol. Fragile and requires hand-tooling every instance.footnotes
package provides the savenote
environment, which can be used to do this.\begin{figure} \begin{minipage}{\textwidth} ... \caption[Caption for LOF]% {Real caption\footnote{blah}} \end{minipage} \end{figure}
Additional reference: TeX FAQ item Footnotes in tables.
FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
Try This Simple and Effective
.home > span + .red{
border:1px solid red;
}
You should have to add only minViewMode: "months"
in your datepicker function.
Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.
There are two possible ways to solve the error:
Disable UnobtrusiveValidationMode
:
Add this to web.config:
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.
Another solution is to register the script:
In Global.asax Application_Start
add mapping to your jQuery file path:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition
{
Path = "~/scripts/jquery-1.7.2.min.js",
DebugPath = "~/scripts/jquery-1.7.2.js",
CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
});
}
Some details from MSDN:
ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.
If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic.
If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.
Take a look on a free tool - Valentina Studio. Amazing product! IMO this is the best manager for SQLite for all platforms:
Also it works on Mac OS X, you can install Valentina Studio (FREE) directly from Mac App Store:
How about this:
df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5],
'col2' : [10, 11, 12, 13, 14]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3],
'col2' : [10, 11, 12]})
records_df2 = set([tuple(row) for row in df2.values])
in_df2_mask = np.array([tuple(row) in records_df2 for row in df1.values])
result = df1[~in_df2_mask]
$('#dropdown_id').find('option').length
on OSX assure you have launched the Docker application before issuing
docker ps
or docker build
... etc ... yes it seems strange and somewhat misleading that issuing
docker --version
gives version even though the docker daemon is not running ... ditto for those other version cmds ... I just encountered exactly the same symptoms ... this behavior on OSX is different from on linux
Toward this same directions, I'm posting a client and server snipets that send Excel Files using WebApi, c# 4:
public static void SetFile(String serviceUrl, byte[] fileArray, String fileName)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var content = new MultipartFormDataContent())
{
var fileContent = new ByteArrayContent(fileArray);//(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
var result = client.PostAsync(serviceUrl, content).Result;
}
}
}
catch (Exception e)
{
//Log the exception
}
}
And the server webapi controller:
public Task<IEnumerable<string>> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
string fullPath = HttpContext.Current.Server.MapPath("~/uploads");
MyMultipartFormDataStreamProvider streamProvider = new MyMultipartFormDataStreamProvider(fullPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return "File uploaded as " + info.FullName + " (" + info.Length + ")";
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
}
}
And the Custom MyMultipartFormDataStreamProvider, needed to customize the Filename:
PS: I took this code from another post http://www.codeguru.com/csharp/.net/uploading-files-asynchronously-using-asp.net-web-api.htm
public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string fileName;
if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
{
fileName = headers.ContentDisposition.FileName;
}
else
{
fileName = Guid.NewGuid().ToString() + ".data";
}
return fileName.Replace("\"", string.Empty);
}
}
Eureka ! Finally I found a solution on this.
This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.
Start >> All Programs >> Accessories >> System Tools >> System Restore.
And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)
in standart Vi editor in this situation you should
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
Solution
To see the option for USB debugging mode in Nexus 4 or Android 4.2 or higher OS, do the following:
Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.
CONCLUSION
That was easy. The best part is you only have to do the tap-build-number-seven-times once. After you do it once, USB debugging has been unlocked and you can enable or disable at your leisure. Please restart after done these steps.
Additional information
Setting up a Device for Development native documentation of Google Android developer site
Update: Google Pixel 3
If you need to facilitate a connection between your device and a computer with the Android SDK (software development kit), view this info.
Doc by Verizon: Original source
Issue comes when any application you want to run needs python 32 bit variants and you have 64 bit variant
Note : Once you install python 32 bit variant,dont forget to install all required packages using pip of this new python 32 bit variant
try this:
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Try Like This: For SQL SERVER 2008+
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'
Or
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MyName%'
Or Something Like This:
SELECT name
FROM sys.tables
WHERE OBJECT_ID IN ( SELECT id
FROM syscolumns
WHERE name like '%COlName%' )
git-subtree
is nice, but it is probably not the one you want.
For example, if projectA
is the directory created in B, after git subtree
,
git log projectA
lists only one commit: the merge. The commits from the merged project are for different paths, so they don't show up.
Greg Hewgill's answer comes closest, although it doesn't actually say how to rewrite the paths.
The solution is surprisingly simple.
(1) In A,
PREFIX=projectA #adjust this
git filter-branch --index-filter '
git ls-files -s |
sed "s,\t,&'"$PREFIX"'/," |
GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info &&
mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE
' HEAD
Note: This rewrites history; you may want to first make a backup of A.
Note Bene: You have to modify the substitute script inside the sed command in the case that you use non-ascii characters (or white characters) in file names or path. In that case the file location inside a record produced by "ls-files -s" begins with quotation mark.
(2) Then in B, run
git pull path/to/A
Voila! You have a projectA
directory in B. If you run git log projectA
, you will see all commits from A.
In my case, I wanted two subdirectories, projectA
and projectB
. In that case, I did step (1) to B as well.
Generally, there is a mistake in the HTTP verb used eg:
Calling PUT
route with POST
request
I'll add a map and filter version because why not.
sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))
public class State
{
public int SID { get; set; }
public string SName { get; set; }
public string SCode { get; set; }
public string SAbbrevation { get; set; }
}
public class Country
{
public int CID { get; set; }
public string CName { get; set; }
public string CAbbrevation { get; set; }
}
List<State> states = new List<State>()
{
new State{ SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
new State{ SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
};
List<Country> coutries = new List<Country>()
{
new Country{CID=1,CName="India",CAbbrevation="IND"},
new Country{CID=2,CName="US of America",CAbbrevation="USA"},
};
var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();
Does this work without alternation?
^((part)1(, \22)?)?(part2)?$
or why not this?
^((part)1(, (\22))?)?(\4)?$
The first works for all conditions the second for all but part2
(using GNU sed 4.1.5)
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
This is working as documented. Any paths specified in PYTHONPATH
are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append()
appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:
import sys
sys.path.insert(0,'/path/to/mod_directory')
That said, there are usually better ways to manage imports than either using PYTHONPATH
or manipulating sys.path
directly. See, for example, the answers to this question.
targetList = sourceList.stream().flatmap(List::stream).collect(Collectors.toList());
What do you mean with "without iterating"?
You can use map.entrySet().iterator().next()
and you wouldn't iterate through map (in the meaning of "touching each object"). You can't get hold of an Entry<K, V>
without using an iterator though. The Javadoc of Map.Entry says:
The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration.
Can you explain in more detail, what you are trying to accomplish? If you want to handle objects first, that match a specific criterion (like "have a particular key") and fall back to the remaining objects otherwise, then look at a PriorityQueue. It will order your objects based on natural order or a custom-defined Comparator
that you provide.
Try:
//category[@name='Sport' and ./author/text()='James Small']
It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this
For example, in your component before you declare your @Component
const en = require('../assets/en.json');
Addition after very useful comment of mhand at the end
Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.
The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:
public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
(this IEnumerable<TSource> source, int chunkSize)
{
while (source.Any()) // while there are elements left
{ // still something to chunk:
yield return source.Take(chunkSize); // return a chunk of chunkSize
source = source.Skip(chunkSize); // skip the returned chunk
}
}
Suppose you divide your source into chunks of chunkSize
. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.
While(source.Any())
{
...
}
the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times
yield return source.Take(chunkSize);
According to the reference source this will do something like:
public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
return TakeIterator<TSource>(source, count);
}
static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
foreach (TSource element in source)
{
yield return element;
if (--count == 0) break;
}
}
This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.
If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:
After the first chunk has been yield returned, we skip this first Chunk:
source = source.Skip(chunkSize);
Once again: we'll take a look at reference source to find the skipiterator
static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (count > 0 && e.MoveNext()) count--;
if (count <= 0)
{
while (e.MoveNext()) yield return e.Current;
}
}
}
As you see, the SkipIterator
calls MoveNext()
once for every element in the Chunk. It doesn't call Current
.
So per Chunk we see that the following is done:
Take():
If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;
Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator
If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current
for the TSource items you actually decide to access.
If you take N Chunks of size chunkSize, then calls to MoveNext()
If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.
The total
MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)
So if you decide to enumerate all elements of all chunks:
MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once
Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.
But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.
It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks
You're looking for the OpenFileDialog
class.
For example:
Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
Using dialog As New OpenFileDialog
If dialog.ShowDialog() <> DialogResult.OK Then Return
File.Copy(dialog.FileName, newPath)
End Using
End Sub
In a ASP.NET Core project you can use the QueryHelpers
class, available in the Microsoft.AspNetCore.WebUtilities
namespace for ASP.NET Core, or the .NET Standard 2.0 NuGet package for other consumers:
// using Microsoft.AspNetCore.WebUtilities;
var query = new Dictionary<string, string>
{
["foo"] = "bar",
["foo2"] = "bar2",
// ...
};
var response = await client.GetAsync(QueryHelpers.AddQueryString("/api/", query));
Its seems that server is not running properly so ensure that with terminal by
telnet ip port
example
telnet localhost 8069
It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection
Git has the concept of "remotes", which are simply URLs to other copies of your repository. When you clone another repository, Git automatically creates a remote named "origin" and points to it.
You can see more information about the remote by typing git remote show origin
.
well here is common usage of getter setter in actual use case,
public class OrderItem
{
public int Id {get;set;}
public int quantity {get;set;}
public int Price {get;set;}
public int TotalAmount {get {return this.quantity *this.Price;}set;}
}
Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.
If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.
The most important concern about private methods and attributes is to tell developers not to call it outside the class and this is encapsulation. one may misunderstand security from encapsulation. when one deliberately uses syntax like that(bellow) you mentioned, you do not want encapsulation.
obj._MyClass__myPrivateMethod()
I have migrated from C# and at first it was weird for me too but after a while I came to the idea that only the way that Python code designers think about OOP is different.
On macOS, go to the git root directory and enter git diff *
You can plot the means without resorting to external calculations and additional tables using stat_summary(...)
. In fact, stat_summary(...)
was designed for exactly what you are doing.
library(ggplot2)
library(reshape2) # for melt(...)
gg <- melt(df,id="gender") # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) +
stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) +
scale_color_discrete("Gender")
stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
color="grey80",position=position_dodge(1), width=.2)
To add "error bars" you cna also use stat_summary(...)
(here, I'm using the min and max value rather than sd because you have so little data).
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) +
stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) +
stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
color="grey40",position=position_dodge(1), width=.2) +
scale_fill_discrete("Gender")
I already found it:
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_name='mytable'
Here is a basic example that explains the callback()
function in JavaScript:
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
if (callback && typeof(callback) === "function") {_x000D_
x += 1;_x000D_
alert("Calla Back x= " + x);_x000D_
x += 1;_x000D_
callback();_x000D_
}_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
alert("Function X= " + x);_x000D_
});
_x000D_
It's simple use:
long millis = new Date().getTime();
if you want it in particular format then you need Formatter like below
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString = dateFormat.format(new Date());
this is a select command
FROM
user
WHERE
application_key = 'dsfdsfdjsfdsf'
AND email NOT LIKE '%applozic.com'
AND email NOT LIKE '%gmail.com'
AND email NOT LIKE '%kommunicate.io';
this update command
UPDATE user
SET email = null
WHERE application_key='dsfdsfdjsfdsf' and email not like '%applozic.com'
and email not like '%gmail.com' and email not like '%kommunicate.io';
Swift 3
let parsedResult: [String: AnyObject]
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
} catch {
// Display an error or return or whatever
}
data - it's Data type (Structure) (i.e. returned by some server response)
Some date utilities, including comparisons IN ENGLISH, which is nice:
#import <Foundation/Foundation.h>
@interface NSDate (Util)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
- (NSDate*) dateByAddingDays:(int)days;
@end
The implementation:
#import "NSDate+Util.h"
@implementation NSDate (Util)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
- (NSDate *) dateByAddingDays:(int)days {
NSDate *retVal;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:days];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
retVal = [gregorian dateByAddingComponents:components toDate:self options:0];
return retVal;
}
@end
def awgn(sinal):
regsnr=54
sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
sigpower=sigpower/len(sinal)
noisepower=sigpower/(math.pow(10,regsnr/10))
noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
return noise
I was using ADO.NET and was using SQL Command as:
string query =
"SELECT * " +
"FROM table_name" +
"Where id=@id";
the thing was i missed a whitespace at the end of "FROM table_name"+
So basically it said
string query = "SELECT * FROM table_nameWHERE id=@id";
and this was causing the error.
Hope it helps
I'm not sure what changed, but I am unable to checkout a specific commit without the option --detach
. The full command that worked for me was:
git checkout --detach [commit hash]
To get back from the detached state I had to checkout my local branch: git checkout master
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence use printf
instead.
If none of the above solutions are working, try manually adding "http://" to the beginning of the url.
Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).
SELECT length(actual_project_name),actual_project_name,
SUBSTRING_INDEX(actual_project_name,'-',1) as aaaaaa,
SUBSTRING_INDEX(actual_project_name, '-', -1) as actual_project_number,
concat(SUBSTRING_INDEX(actual_project_name,'-',1),SUBSTRING_INDEX(actual_project_name, '-', -1)) as a
FROM ctts.test22
order by
SUBSTRING_INDEX(actual_project_name,'-',1) asc,cast(SUBSTRING_INDEX(actual_project_name, '-', -1) as unsigned) asc
try to implement with javascript this:
<div id="mydiv" onclick="myhref('http://web.com');" >some stuff </div>
<script type="text/javascript">
function myhref(web){
window.location.href = web;}
</script>
you are going to want to separate your arguments into separate parameter
$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"
$arguments = "/v:q /nologo"
start-process $msbuild $arguments
You don't, as serialize is meant to be used as an query string, and in that context, unchecked means it's not in the querystring at all.
If you really want to get the values of unchecked checkboxes, use: (untested off course)
var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function(){return this.value}).get();
To convert from hex to decimal, there are many ways to do it in the shell or with an external program:
With bash:
$ echo $((16#FF))
255
with bc:
$ echo "ibase=16; FF" | bc
255
with perl:
$ perl -le 'print hex("FF");'
255
with printf :
$ printf "%d\n" 0xFF
255
with python:
$ python -c 'print(int("FF", 16))'
255
with ruby:
$ ruby -e 'p "FF".to_i(16)'
255
with node.js:
$ nodejs <<< "console.log(parseInt('FF', 16))"
255
with rhino:
$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255
with groovy:
$ groovy -e 'println Integer.parseInt("FF",16)'
255
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKind(of: LoginViewController.self) {
}
}
}
Also you can position the other window before withdrawing it so that you position your message
from tkinter import *
import tkinter.messagebox
window = Tk()
window.wm_withdraw()
# message at x:200,y:200
window.geometry("1x1+200+200") # remember its.geometry("WidthxHeight(+or-)X(+or-)Y")
tkinter.messagebox.showerror(title="error", message="Error Message", parent=window)
# center screen message
window.geometry(f"1x1+{round(window.winfo_screenwidth() / 2)}+{round(window.winfo_screenheight() / 2)}")
tkinter.messagebox.showinfo(title="Greetings", message="Hello World!")
Please Note: This is Lewis Cowles' answer just Python 3ified, since tkinter has changed since python 2. If you want your code to be backwords compadible do something like this:
try:
import tkinter
import tkinter.messagebox
except ModuleNotFoundError:
import Tkinter as tkinter
import tkMessageBox as tkinter.messagebox
I realized that several answers have been provided but no real fix yet.
The reason, as mentioned above, is a "End of line" missing at the end of the CSV file.
While the real Fix should come from Microsoft, the walk around is to open the CSV file with a Text-editor and add a line at the end of the file (aka press return key). I use ATOM software as a text/code editor but virtually all basic text editor would do.
In the meanwhile, please report the bug to Microsoft.
Question: It seems to me that it is a office 2016 problem. Does anyone have the issue on a PC?
There are two different notations to access object properties
Dot notation is fast and easy but you must use the actual property name explicitly. No substitution, variables, etc.
Bracket notation is open ended. It uses a string but you can produce the string using any legal js code. You may specify the string as literal (though in this case dot notation would read easier) or use a variable or calculate in some way.
So, these all set the myObj property named prop1 to the value Hello:
// quick easy-on-the-eye dot notation
myObj.prop1 = "Hello";
// brackets+literal
myObj["prop1"] = "Hello";
// using a variable
var x = "prop1";
myObj[x] = "Hello";
// calculate the accessor string in some weird way
var numList = [0,1,2];
myObj[ "prop" + numList[1] ] = "Hello";
Pitfalls:
myObj.[xxxx] = "Hello"; // wrong: mixed notations, syntax fail
myObj[prop1] = "Hello"; // wrong: this expects a variable called prop1
tl;dnr: If you want to compute or reference the key you must use bracket notation. If you are using the key explicitly, then use dot notation for simple clear code.
Note: there are some other good and correct answers but I personally found them a bit brief coming from a low familiarity with JS on-the-fly quirkiness. This might be useful to some people.
If you need to mutate the dictionary while enumerating:
for (NSString* key in xyz.allKeys) {
[xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}
I think table-cell
needs to have a parent display:table
element.
It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.
And if I miss-read the question then I humbly accept the votes down. (Still good to know though)
Please consider the following code:
#some_div_or_body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
There are some alternatives that can be used with a little bit peace of mind by using jQuery:
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
I hope this helps!
In pack explorer of eclipse> Single Click on the name of Package> click F2 keyboard key >type new name> click finish.
Eclipse will do the rest of job. It will rename old package name to new in code files also.
Wrote a quick TDD Test for this
[TestMethod]
public void Test()
{
var input = @"ProjectName\Iteration\Release1\Iteration1";
var pattern = @"\\Iteration";
var rgx = new Regex(pattern);
var result = rgx.Replace(input, "", 1);
Assert.IsTrue(result.Equals(@"ProjectName\Release1\Iteration1"));
}
rgx.Replace(input, "", 1); says to look in input for anything matching the pattern, with "", 1 time.
If we just use normal HTML image tag like this it is working. I use this in website made with Jekyll.
<img class="img-fluid" src="./img/face.jpg" alt="img-verification">
If we add bootstrap classes as per this example it works fine.
A year later, stumbled across this question for a inline LI
problem, but have found a great solution that may apply here.
http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/
vertical-align:bottom
on all my LI
elements fixed my "extra margin" problem in all browsers.
For Unix
grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml
And the output is:
<PROPERTY NAME="ARCHITECTURE" VAL="64"/>
For Windows
findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml
And the output can be:
<PROPERTY NAME="ARCHITECTURE" VAL="64"/>
Writing JSON to a File
import json
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Reading JSON from a File
import json
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')
Regex with replaceAll.
public class Main
{
public static void main(final String[] argv)
{
String str;
str = "hello\r\njava\r\nbook";
str = str.replaceAll("(\\r|\\n)", "");
System.out.println(str);
}
}
If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:
str = str.replaceAll("\\r\\n", "");
To clear from the current position to the end of the current line, do this:
public static void ClearToEndOfCurrentLine()
{
int currentLeft = Console.CursorLeft;
int currentTop = Console.CursorTop;
Console.Write(new String(' ', Console.WindowWidth - currentLeft));
Console.SetCursorPosition(currentLeft, currentTop);
}
ArrayList
has a indexOf()
method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf()
will return exactly what your method returns, fast.
use
npm install -g angular-cli
instead of
npm install -g@nagular/cli
to install Angular
You can reach each separate container using .parent()
API.
Like,
var highestBox = 0;
$('.container .column').each(function(){
if($(this).parent().height() > highestBox){
highestBox = $(this).height();
}
});
You can do it like this -
let arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" },_x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));_x000D_
_x000D_
console.log(arr3);
_x000D_
Use below code if arr1
and arr2
are in a different order:
let arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" }, _x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
merged.push({_x000D_
...arr1[i], _x000D_
...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}_x000D_
);_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
Use this if arr1
and arr2
are in a same order
let arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" }, _x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
merged.push({_x000D_
...arr1[i], _x000D_
...arr2[i]_x000D_
});_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
In Swift 5, you can utilize dot notation for a bit quicker syntax:
myButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
Otherwise, you'll use:
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
For whatever reason, @import didn't work for me, but it's not really necessary is it?
Here's what I did instead, within the html:
<link rel="stylesheet" media="print" href="myap-print.css">
<link rel="stylesheet" media="print" href="myap-screen.css">
<link rel="stylesheet" media="screen" href="myap-screen.css">
Notice that media="print" has 2 stylesheets: myap-print.css and myap-screen.css. It's the same effect as including myap-screen.css within myap-print.css.
I have employed a slightly different technique in my aspnet MVC 4 site:
_ViewStart.cshtml:
@using System.Web.Caching
@using System.Web.Hosting
@{
Layout = "~/Views/Shared/_Layout.cshtml";
PageData.Add("scriptFormat", string.Format("<script src=\"{{0}}?_={0}\"></script>", GetDeployTicks()));
}
@functions
{
private static string GetDeployTicks()
{
const string cacheKey = "DeployTicks";
var returnValue = HttpRuntime.Cache[cacheKey] as string;
if (null == returnValue)
{
var absolute = HostingEnvironment.MapPath("~/Web.config");
returnValue = File.GetLastWriteTime(absolute).Ticks.ToString();
HttpRuntime.Cache.Insert(cacheKey, returnValue, new CacheDependency(absolute));
}
return returnValue;
}
}
Then in the actual views:
@Scripts.RenderFormat(PageData["scriptFormat"], "~/Scripts/Search/javascriptFile.min.js")
Command line arguments are stored as strings in the String
array String[] args that is passed to
main()`.
java [program name] [arg1,arg2 ,..]
Command line arguments are the inputs that accept from the command prompt while running the program. The arguments passed can be anything. Which is stored in the args[]
array.
//Display all command line information
class ArgDemo{
public static void main(String args[]){
System.out.println("there are "+args.length+"command-line arguments.");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}
Example:
java Argdemo one two
The output will be:
there are 2 command line arguments:
they are:
arg[0]:one
arg[1]:two
You can also create a shortcut on desktop that can run a specific command or even a batch file by just typing the command in "Type the Location of Item" bar in create shortcut wizard
This may be a bit off-topic but I want to share it here because I simply wanted to remove Alerts from state after a given timeout i.e. auto hiding alerts/notifications.
I ended up using setTimeout()
within the <Alert />
component, so that it can then call and dispatch a REMOVE
action on given id
.
export function Alert(props: Props) {
useEffect(() => {
const timeoutID = setTimeout(() => {
dispatchAction({
type: REMOVE,
payload: {
id: id,
},
});
}, timeout ?? 2000);
return () => clearTimeout(timeoutID);
}, []);
return <AlertComponent {...props} />;
}
Source article: Passing a list as an argument to a vararg method
Use the toArray(T[] arr)
method.
.getMap(locations.toArray(new WorldLocation[locations.size()]))
(toArray(new WorldLocation[0])
also works, but you would allocate a zero-length array for no reason.)
Here's a complete example:
public static void method(String... strs) {
for (String s : strs)
System.out.println(s);
}
...
List<String> strs = new ArrayList<String>();
strs.add("hello");
strs.add("world");
method(strs.toArray(new String[strs.size()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
That is invalid syntax. You are mixing relational expressions with scalar operators (OR
). Specifically you cannot combine expr IN (select ...) OR (select ...)
. You probably want expr IN (select ...) OR expr IN (select ...)
. Using union would also work: expr IN (select... UNION select...)
When you do this,
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
You consume everything in instream, so instream is empty. Now when try to do this,
Document doc = builder.parse(instream);
The parsing will fail, because you have passed it an empty stream.
Perhaps the volume was created via docker-compose
? If so, it should get removed by:
docker-compose down --volumes
Credit to Niels Bech Nielsen!
This forum suggests also:
SELECT CATALOG_NAME AS DataBaseName FROM INFORMATION_SCHEMA.SCHEMATA
Note that the if $myVar; then ... ;fi
construct has a security problem you might want to avoid with
case $myvar in
(true) echo "is true";;
(false) echo "is false";;
(rm -rf*) echo "I just dodged a bullet";;
esac
You might also want to rethink why if [ "$myvar" = "true" ]
appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case
solution is also handled without forks.
The IPv6 addresses for fields like RemoteAddr
from http.Request
are formatted as "[::1]:53343"
So net.SplitHostPort
works great:
package main
import (
"fmt"
"net"
)
func main() {
host1, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host1, port, err)
host2, port, err := net.SplitHostPort("[::1]:2345")
fmt.Println(host2, port, err)
host3, port, err := net.SplitHostPort("localhost:1234")
fmt.Println(host3, port, err)
}
Output is:
127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>
If you are using Spring MVC version 5 you can set the encoding also using the @GetMapping
annotation. Here is an example which sets the content type to JSON and also the encoding type to UTF-8:
@GetMapping(value="/rest/events", produces = "application/json; charset=UTF-8")
More information on the @GetMapping annotation here:
What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj
and zlib.decompressobj
with the zdict
parameter set to your "base word", e.g. afrykanerskojezyczny
.
Caveats are zdict
is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.
You can also "sample" the same number of items in your data frame with something like this:
nr<-dim(M)[1]
random_M = M[sample.int(nr),]
If you really don't want to include top directory in the tarball (and that's generally bad idea):
tar czf workspace.tar.gz -C /path/to/workspace .
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
Most of the answers found here are correct only if you need the current year based on your local machine's time zone and offset (client side) - source which, in most scenarios, cannot be considered reliable (beause it can differ from machine to machine).
Reliable sources are:
A method called on the Date
instance will return a value based on the local time of your machine.
Further details can be found in "MDN web docs": JavaScript Date object.
For your convenience, I've added a relevant note from their docs:
(...) the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.
Another source mentioning this is: JavaScript date and time object
it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.
Some reliable sources that you can use are:
But if you simply don't care about the time accuracy or if your use case requires a time value relative to local machine's time then you can safely use Javascript's Date
basic methods like Date.now()
, or new Date().getFullYear()
(for current year).
While the currently accepted answer was a huge help to me, I wanted to share some useful modifications that simplify the queries and also increase performance.
To handle events which recur at regular intervals, such as:
Repeat every other day
or
Repeat every week on Tuesday
You should create two tables, one called events
like this:
ID NAME
1 Sample Event
2 Another Event
And a table called events_meta
like this:
ID event_id repeat_start repeat_interval
1 1 1369008000 604800 -- Repeats every Monday after May 20th 2013
1 1 1369008000 604800 -- Also repeats every Friday after May 20th 2013
With repeat_start
being a unix timestamp date with no time (1369008000 corresponds to May 20th 2013) , and repeat_interval
an amount in seconds between intervals (604800 is 7 days).
By looping over each day in the calendar you can get repeat events using this simple query:
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE (( 1299736800 - repeat_start) % repeat_interval = 0 )
Just substitute in the unix-timestamp (1299736800) for each date in your calendar.
Note the use of the modulo (% sign). This symbol is like regular division, but returns the ''remainder'' instead of the quotient, and as such is 0 whenever the current date is an exact multiple of the repeat_interval from the repeat_start.
This is significantly faster than the previously suggested "meta_keys"-based answer, which was as follows:
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
AND (
( CASE ( 1299132000 - EM1.`meta_value` )
WHEN 0
THEN 1
ELSE ( 1299132000 - EM1.`meta_value` )
END
) / EM2.`meta_value`
) = 1
If you run EXPLAIN this query, you'll note that it required the use of a join buffer:
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| 1 | SIMPLE | EM1 | ALL | NULL | NULL | NULL | NULL | 2 | Using where |
| 1 | SIMPLE | EV | eq_ref | PRIMARY | PRIMARY | 4 | bcs.EM1.event_id | 1 | |
| 1 | SIMPLE | EM2 | ALL | NULL | NULL | NULL | NULL | 2 | Using where; Using join buffer |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
The solution with 1 join above requires no such buffer.
You can add support for more complex types to support these types of repeat rules:
Event A repeats every month on the 3rd of the month starting on March 3, 2011
or
Event A repeats second Friday of the month starting on March 11, 2011
Your events table can look exactly the same:
ID NAME
1 Sample Event
2 Another Event
Then to add support for these complex rules add columns to events_meta
like so:
ID event_id repeat_start repeat_interval repeat_year repeat_month repeat_day repeat_week repeat_weekday
1 1 1369008000 604800 NULL NULL NULL NULL NULL -- Repeats every Monday after May 20, 2013
1 1 1368144000 604800 NULL NULL NULL NULL NULL -- Repeats every Friday after May 10, 2013
2 2 1369008000 NULL 2013 * * 2 5 -- Repeats on Friday of the 2nd week in every month
Note that you simply need to either specify a repeat_interval
or a set of repeat_year
, repeat_month
, repeat_day
, repeat_week
, and repeat_weekday
data.
This makes selection of both types simultaneously very simple. Just loop through each day and fill in the correct values, (1370563200 for June 7th 2013, and then the year, month, day, week number and weekday as follows):
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE (( 1370563200 - repeat_start) % repeat_interval = 0 )
OR (
(repeat_year = 2013 OR repeat_year = '*' )
AND
(repeat_month = 6 OR repeat_month = '*' )
AND
(repeat_day = 7 OR repeat_day = '*' )
AND
(repeat_week = 2 OR repeat_week = '*' )
AND
(repeat_weekday = 5 OR repeat_weekday = '*' )
AND repeat_start <= 1370563200
)
This returns all events that repeat on the Friday of the 2nd week, as well as any events that repeat every Friday, so it returns both event ID 1 and 2:
ID NAME
1 Sample Event
2 Another Event
*Sidenote in the above SQL I used PHP Date's default weekday indexes, so "5" for Friday
Hope this helps others as much as the original answer helped me!
Same as above, might help some people.
setTimeout(() => {
if (pushToken!=null && deviceId!=null) {
console.log("pushToken & OS ");
this.setState({ pushToken: pushToken});
this.setState({ deviceId: deviceId });
console.log("pushToken & OS "+pushToken+"\n"+deviceId);
}
}, 1000);
Check for any recusive calls for methods. Mainly it is caused when there is recursive call for a method. A simple example is
public static void main(String... args) {
Main main = new Main();
main.testMethod(1);
}
public void testMethod(int i) {
testMethod(i);
System.out.println(i);
}
Here the System.out.println(i); will be repeatedly pushed to stack when the testMethod is called.
1 use command
show create table test.location
There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.
It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.
Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.
original post : Generate UPDATE statement in SQL Server for specific table
CREATE PROCEDURE [dbo].[sp_generate_updates] (
@fullquery nvarchar(max) = '',
@ignore_field_input nvarchar(MAX) = '',
@PK_COLUMN_NAME nvarchar(MAX) = ''
)
AS
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1'' '
OR
SET QUOTED_IDENTIFIER OFF
EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1' "
-- For ignoring specific columns (to ignore in the UPDATE and INSERT SQL statement)
EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1 ' , 'Column01,Column02'
-- For just updates without insert statement (replace the * )
EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1 '
-- For tables without a primary key: construct the key in the third variable
EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1 ' ,'','your_chosen_primary_key_Col1,key_Col2'
-- For complex updates with JOINED tables
EXEC [sp_generate_updates] 'select o1.Name, o1.category, o2.name+ '_hello_world' as #name
from overnightsetting o1
inner join overnightsetting o2 on o1.name=o2.name
where o1.name like '%appserver%'
(REMARK about above: the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )
-------------README for the deeper interested person:
Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
Its power sits also in the fact that you can make insert statements, so combined gives you a "IF NOT EXISTS() INSERT " capability.
The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
The script works with a real temporary table, made on the fly (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" , and the 2 update statement.
We work with temporary structures like "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
example "where columnname = {Columnname}" for birthdate becomes "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
So then the statement becomes "where birthdate = {19800417}"
Enjoy releasing scripts as of now... by Pieter van Nederkassel - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL DROP TABLE #ignore
DECLARE @stringsplit_table TABLE (col nvarchar(255), dtype nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
@pkstring NVARCHAR(512), -- sting to store the primary keys or the idendity key
@table_name nvarchar(512), -- (left) table name, including schema
@table_N_where_clause nvarchar(max), -- tablename
@table_alias nvarchar(512), -- holds the (left) table alias if one available, else @table_name
@table_schema NVARCHAR(30), -- schema of @table_name
@update_list1 NVARCHAR(MAX), -- placeholder for SET fields section of update
@update_list2 NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
@list_all_cols BIT = 0, -- placeholder for values for the insert into table VALUES command
@select_list NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
@COLUMN_NAME NVARCHAR(255), -- will hold column names of the (left) table
@sql NVARCHAR(MAX), -- sql statement variable
@getdate NVARCHAR(17), -- transform getdate() to YYYYMMDDHHMMSSMMM
@tmp_table NVARCHAR(255), -- will hold the name of a physical temp table
@pk_separator NVARCHAR(1), -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
@COLUMN_NAME_DATA_TYPE NVARCHAR(100), -- needed for insert statements to convert to right text string
@own_pk BIT = 0 -- check if table has PK (0) or if provided PK will be used (1)
set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME= replace(replace(replace(@PK_COLUMN_NAME, ' ',''),'[',''),']','')
-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),' ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
print ' WARNING: ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
select ' WARNING: IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
exec (@table_N_where_clause)
set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)
IF CHARINDEX('where ', @table_N_where_clause) > 0 SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ', @table_alias) > 0 SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0 SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 ) set @list_all_cols=1
/*
print @fullquery
print @table_alias
print @table_N_where_clause
print @table_name
*/
-- Prepare PK condition
SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END
SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i1.TABLE_SCHEMA = @table_schema
-- if no primary keys exist then we try for identity columns
IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table
INSERT INTO @stringsplit_table
SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
inner join INFORMATION_SCHEMA.COLUMNS i2
on i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA = i2.TABLE_SCHEMA
WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i1.TABLE_SCHEMA = @table_schema
-- if no primary keys exist then we try for identity columns
IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
FROM INFORMATION_SCHEMA.COLUMNS i2
WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1
AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i2.TABLE_SCHEMA = @table_schema
-- NOW handling the primary key given as parameter to the main batch
SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = ';'
ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = '|'
ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = '-'
SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
INSERT INTO @stringsplit_table
SELECT LTRIM(RTRIM(x.value)) , 'datetime' FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x
SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
FROM @stringsplit_table x
SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
FROM @stringsplit_table x
--print 'pkcolumns '+ isnull(@PK_COLUMN_NAME,'')
update @stringsplit_table set col='pk_' + col
SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove [] from tablename',17,1)
END
-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key
if isnull(@pkstring,'') = '' set @pkstring = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> '' SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring
-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement, in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT ignore_field = 'uniqueidXXXX' INTO #ignore
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM string_split(@ignore_field_input,@pk_separator)
SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','')
SET @sql = replace( @fullquery, ' from ', ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)
SELECT @sql = N'alter table ' + @tmp_table + N' add update_stmt1 nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)
-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') +
CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','')
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
WHERE 1 = 1
AND ku.TABLE_NAME = c2.TABLE_NAME
AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
AND ku.COLUMN_NAME = c2.COLUMN_NAME
AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)
-- Prepare update field list (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') + QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'
-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1 -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+ REPLACE(@table_name,@table_schema+'.','') +' where '+ @PK_condition +') INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','') + '('+ @select_list + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + ''''
if @list_all_cols=1 EXEC (@sql)
--print 'select========== ' + @select_list
--print 'update========== ' + @update_list1
SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
N' SET ' + @update_list1 + N''' + ''' +
N' WHERE ' + @PK_condition + N''') '
EXEC (@sql)
--print @sql
SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
N' SET ' + @update_list2 + N''' + ''' +
N' WHERE ' + @PK_condition + N''') '
EXEC (@sql)
--print @sql
-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
AND TABLE_SCHEMA = @table_schema
UNION--pned
SELECT col, 'datetime' FROM @stringsplit_table
OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql =
CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')) '
ELSE
N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
END
----PRINT @sql
EXEC (@sql)
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns
--SELECT col FROM @stringsplit_table -- these are the primary keys
-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
SELECT COLUMN_NAME,DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @tmp_table -- AND TABLE_SCHEMA = @table_schema
UNION--pned
SELECT col, 'datetime' FROM @stringsplit_table
OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql =
CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')) '
ELSE
N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
END
EXEC (@sql)
----print @sql
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns
SET @sql = 'Select * from ' + @tmp_table + ';'
--exec (@sql)
SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
SELECT ''USE ' + DB_NAME() + ''' as executelist
UNION ALL
SELECT ''GO '' as executelist
UNION ALL
SELECT '' /*PRESCRIPT CHECK */ ' + replace(@fullquery,'''','''''')+''' as executelist
UNION ALL
SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
UNION ALL
SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
UNION ALL
SELECT isnull(update_stmt3, '' add more columns inn query please'') as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
UNION ALL
SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 '' as executelist
UNION ALL
SELECT '' /*VERIFY WITH: */ ' + replace(@fullquery,'''','''''')+''' as executelist
UNION ALL
SELECT ''-- SCRIPT LOCATION: F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql'' as executelist
END'
exec (@sql)
SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)
Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.
import re, sys
class Reprinter:
def __init__(self):
self.text = ''
def moveup(self, lines):
for _ in range(lines):
sys.stdout.write("\x1b[A")
def reprint(self, text):
# Clear previous text by overwritig non-spaces with spaces
self.moveup(self.text.count("\n"))
sys.stdout.write(re.sub(r"[^\s]", " ", self.text))
# Print new text
lines = min(self.text.count("\n"), text.count("\n"))
self.moveup(lines)
sys.stdout.write(text)
self.text = text
reprinter = Reprinter()
reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")