you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
This could result from not setting the correct deployment info. (i.e. if your storyboard isn't set as the main interface)
The ffmpeg wiki links back to this page in reference to "How to split video efficiently". I'm not convinced this page answers that question, so I did as @AlcubierreDrive suggested…
echo "Two commands"
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 -sn test1.mkv
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test2.mkv
echo "One command"
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 \
-sn test3.mkv -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test4.mkv
Which outputs...
Two commands
real 0m16.201s
user 0m1.830s
sys 0m1.301s
real 0m43.621s
user 0m4.943s
sys 0m2.908s
One command
real 0m59.410s
user 0m5.577s
sys 0m3.939s
I tested a SD & HD file, after a few runs & a little maths.
Two commands SD 0m53.94 #2 wins
One command SD 0m49.63
Two commands SD 0m55.00
One command SD 0m52.26 #1 wins
Two commands SD 0m58.60 #2 wins
One command SD 0m58.61
Two commands SD 0m54.60
One command SD 0m50.51 #1 wins
Two commands SD 0m53.94
One command SD 0m49.63 #1 wins
Two commands SD 0m55.00
One command SD 0m52.26 #1 wins
Two commands SD 0m58.71
One command SD 0m58.61 #1 wins
Two commands SD 0m54.63
One command SD 0m50.51 #1 wins
Two commands SD 1m6.67s #2 wins
One command SD 1m20.18
Two commands SD 1m7.67
One command SD 1m6.72 #1 wins
Two commands SD 1m4.92
One command SD 1m2.24 #1 wins
Two commands SD 1m1.73
One command SD 0m59.72 #1 wins
Two commands HD 4m23.20
One command HD 3m40.02 #1 wins
Two commands SD 1m1.30
One command SD 0m59.59 #1 wins
Two commands HD 3m47.89
One command HD 3m29.59 #1 wins
Two commands SD 0m59.82
One command SD 0m59.41 #1 wins
Two commands HD 3m51.18
One command HD 3m30.79 #1 wins
SD file = 1.35GB DVB transport stream
HD file = 3.14GB DVB transport stream
The single command is better if you are handling HD, it agrees with the manuals comments on using -ss after the input file to do a 'slow seek'. SD files have a negligible difference.
The two command version should be quicker by adding another -ss before the input file for the a 'fast seek' followed by the more accurate slow seek.
Not tested, but I think you can do the following:
dataGrid.Rows[index].Selected = true;
or you could do the following (but again: not tested):
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}
To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c
written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.
This is the sort of thing that the CSS flexbox model will fix, because it will let you specify that each li will receive an equal proportion of the remaining width.
Don't put the @ before the id
new { id = "1" }
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route
I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].
int size = 1492;
char (*array)[20];
array = new char[size][20];
...
strcpy(array[5], "hola!");
...
delete [] array;
The key is the parentheses in the array declaration.
The modern way to do it that maintains the order is:
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lseparatedOrbList))
as discussed by Raymond Hettinger (python core dev) in this answer. In python 3.5 and above this is also the fastest way - see the linked answer for details. However the keys must be hashable (as is the case in your list I think)
You could use this to pick all li
elements without class:
$('ul#list li:not([class])')
If the formatting template was read from a file, and you cannot ensure the content doubles the percent sign, then you probably have to detect the percent character and decide programmatically whether it is the start of a placeholder or not. Then the parser should also recognize sequences like %d
(and other letters that can be used), but also %(xxx)s
etc.
Similar problem can be observed with the new formats -- the text can contain curly braces.
It looks like you can add it to your ~/.my.cnf, but it needs to be added as an argument to the init-command flag in your [client] section, like so:
[client]
init-command='set autocommit=0'
Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.
Here is working example in BDD style which is pretty simple and clear
given(carRepository.findByName(any(String.class))).willReturn(Optional.empty()).willReturn(Optional.of(MockData.createCarEntity()));
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
export const authHandler = (config) => {
const authRegex = /^\/apiregex/;
if (!authRegex.test(config.url)) {
return store.fetchToken().then((token) => {
Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
return Promise.resolve(config);
});
}
return Promise.resolve(config);
};
axios.interceptors.request.use(authHandler);
Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:
This solution is generic without reflection overhead.
public static Nullable<T> ParseNullable<T>(string s, Func<string, T> parser) where T : struct
{
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;
else return parser(s);
}
static void Main(string[] args)
{
Nullable<int> i = ParseNullable("-1", int.Parse);
Nullable<float> dt = ParseNullable("3.14", float.Parse);
}
private void button6_Click(object sender, EventArgs e)
{
//create With Input FileNames
AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");
//create with input stream
AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem(File.ReadAllBytes( @"E:\b\1.jpg"),@"images\1.jpg"),
new ZipItem(File.ReadAllBytes(@"E:\b\2.txt"),@"text\2.txt")}, @"C:\test.zip");
//Create Archive And Return StreamZipFile
MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
new ZipItem(@"E:\b\2.txt",@"text\2.txt")});
//Extract in memory
ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");
//Choese Files For Extract To memory
List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);
// Choese Files For Extract To Directory
ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");
}
public struct ZipItem
{
string _FileNameSource;
string _PathinArchive;
byte[] _Bytes;
public ZipItem(string __FileNameSource, string __PathinArchive)
{
_Bytes=null ;
_FileNameSource = __FileNameSource;
_PathinArchive = __PathinArchive;
}
public ZipItem(byte[] __Bytes, string __PathinArchive)
{
_Bytes = __Bytes;
_FileNameSource = "";
_PathinArchive = __PathinArchive;
}
public string FileNameSource
{
set
{
FileNameSource = value;
}
get
{
return _FileNameSource;
}
}
public string PathinArchive
{
set
{
_PathinArchive = value;
}
get
{
return _PathinArchive;
}
}
public byte[] Bytes
{
set
{
_Bytes = value;
}
get
{
return _Bytes;
}
}
}
public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
{
MemoryStream memoryStream = new MemoryStream();
//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);
foreach (ZipItem item in ZipItems)
{
//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);
//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();
//Read Stream
FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 0;
while (fsReader.Position != fsReader.Length)
{
//Read Bytes
ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);
//Write Bytes
OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
}
fsReader.Dispose();
OpenFileInArchive.Close();
}
archive.Dispose();
using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
public MemoryStream AddFileToArchive(ZipItem[] ZipItems)
{
MemoryStream memoryStream = new MemoryStream();
//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);
foreach (ZipItem item in ZipItems)
{
//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);
//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();
//Read Stream
FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 0;
while (fsReader.Position != fsReader.Length)
{
//Read Bytes
ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);
//Write Bytes
OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
}
fsReader.Dispose();
OpenFileInArchive.Close();
}
archive.Dispose();
return memoryStream;
}
public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
{
MemoryStream memoryStream = new MemoryStream();
//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);
foreach (ZipItem item in ZipItems)
{
//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);
//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();
//Read Stream
// FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 4096 ;int TotalWrite=0;
while (TotalWrite != item.Bytes.Length)
{
if(TotalWrite+4096>item.Bytes.Length)
ReadByte=item.Bytes.Length-TotalWrite;
Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);
//Write Bytes
OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
TotalWrite += ReadByte;
}
OpenFileInArchive.Close();
}
archive.Dispose();
using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
public MemoryStream AddFileToArchive_InputByte(ZipItem[] ZipItems)
{
MemoryStream memoryStream = new MemoryStream();
//Create Empty Archive
ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);
foreach (ZipItem item in ZipItems)
{
//Create Path File in Archive
ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);
//Open File in Archive For Write
var OpenFileInArchive = FileInArchive.Open();
//Read Stream
// FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 4096 ;int TotalWrite=0;
while (TotalWrite != item.Bytes.Length)
{
if(TotalWrite+4096>item.Bytes.Length)
ReadByte=item.Bytes.Length-TotalWrite;
Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);
//Write Bytes
OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
TotalWrite += ReadByte;
}
OpenFileInArchive.Close();
}
archive.Dispose();
return memoryStream;
}
public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
{
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
{
if (Directory.Exists(destinationDirectoryName)==false )
Directory.CreateDirectory(destinationDirectoryName);
//Loops through each file in the zip file
archive.ExtractToDirectory(destinationDirectoryName);
}
}
public void ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
{
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
if (PosResult != -1)
{
//Create Folder
if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));
Stream OpenFileGetBytes = file.Open();
FileStream FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 0; int TotalRead = 0;
while (TotalRead != file.Length)
{
//Read Bytes
ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
TotalRead += ReadByte;
//Write Bytes
FileStreamOutput.Write(ReadAllbytes, 0, ReadByte);
}
FileStreamOutput.Close();
OpenFileGetBytes.Close();
_PathFilesinArchive.RemoveAt(PosResult);
}
if (_PathFilesinArchive.Count == 0)
break;
}
}
}
public ZipItem[] ExtractItems(string sourceArchiveFileName)
{
List< ZipItem> ZipItemsReading = new List<ZipItem>();
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
Stream OpenFileGetBytes = file.Open();
MemoryStream memstreams = new MemoryStream();
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 0; int TotalRead = 0;
while (TotalRead != file.Length)
{
//Read Bytes
ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
TotalRead += ReadByte;
//Write Bytes
memstreams.Write(ReadAllbytes, 0, ReadByte);
}
memstreams.Position = 0;
OpenFileGetBytes.Close();
memstreams.Dispose();
ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));
}
}
return ZipItemsReading.ToArray();
}
public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
{
List< ZipItem> ZipItemsReading = new List<ZipItem>();
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
if (PosResult!= -1)
{
Stream OpenFileGetBytes = file.Open();
MemoryStream memstreams = new MemoryStream();
byte[] ReadAllbytes = new byte[4096];//Capcity buffer
int ReadByte = 0; int TotalRead = 0;
while (TotalRead != file.Length)
{
//Read Bytes
ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
TotalRead += ReadByte;
//Write Bytes
memstreams.Write(ReadAllbytes, 0, ReadByte);
}
//Create item
ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));
OpenFileGetBytes.Close();
memstreams.Dispose();
_PathFilesinArchive.RemoveAt(PosResult);
}
if (_PathFilesinArchive.Count == 0)
break;
}
}
return ZipItemsReading.ToArray();
}
This should give what you want:
FLOOR(RAND() * 401) + 100
Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min>
generates a number between <min
> and <max>
inclusive.
Update
This full statement should work:
SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number`
FROM users
Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.
Here is how I did it:
d3.select("div#chartId")_x000D_
.append("div")_x000D_
// Container class to make it responsive._x000D_
.classed("svg-container", true) _x000D_
.append("svg")_x000D_
// Responsive SVG needs these 2 attributes and no width and height attr._x000D_
.attr("preserveAspectRatio", "xMinYMin meet")_x000D_
.attr("viewBox", "0 0 600 400")_x000D_
// Class to make it responsive._x000D_
.classed("svg-content-responsive", true)_x000D_
// Fill with a rectangle for visualization._x000D_
.append("rect")_x000D_
.classed("rect", true)_x000D_
.attr("width", 600)_x000D_
.attr("height", 400);
_x000D_
.svg-container {_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
width: 100%;_x000D_
padding-bottom: 100%; /* aspect ratio */_x000D_
vertical-align: top;_x000D_
overflow: hidden;_x000D_
}_x000D_
.svg-content-responsive {_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
top: 10px;_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
svg .rect {_x000D_
fill: gold;_x000D_
stroke: steelblue;_x000D_
stroke-width: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<div id="chartId"></div>
_x000D_
Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.
More info / tutorials:
http://thenewcode.com/744/Make-SVG-Responsive
http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Service Description";
this.DisplayName = "Service Name";
this.ServiceName = "ServiceName";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
Using the :before
pseudo-element,
CSS3's border-radius
,
and some transparency is quite easy:
<div class="circle"></div>
CSS:
.circle, .circle:before{
position:absolute;
border-radius:150px;
}
.circle{
width:200px;
height:200px;
z-index:0;
margin:11%;
padding:40px;
background: hsla(0, 100%, 100%, 0.6);
}
.circle:before{
content:'';
display:block;
z-index:-1;
width:200px;
height:200px;
padding:44px;
border: 6px solid hsla(0, 100%, 100%, 0.6);
/* 4px more padding + 6px border = 10 so... */
top:-10px;
left:-10px;
}
The :before
attaches to our .circle
another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.
if (x instanceof Collection<?>){
}
if (x instanceof Map<?,?>){
}
I'd suggest instead of doing another query with the same parameters just immediately running a SELECT FOUND_ROWS()
just remove this because constructor don't have a return type like void it will be like this :
private Flow()
{
X = x;
Y = y;
}
Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:
Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.
Many people have answered the mechanical details already, but it's worth noting: This is a poor design choice, by Java.
Java's asList
method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add
method, it throws an UnsupportedOperationException
. This is unintuitive behavior! If a method says it returns a List
, the standard expectation is that it returns an object which supports the methods of interface List
. A developer shouldn't have to memorize which of the umpteen util.List
methods create List
s that don't actually support all the List
methods.
If they had named the method asImmutableList
, it would make sense. Or if they just had the method return an actual List
(and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the Principle of Least Surprise and the good-O.O. practice of avoiding UnsupportedOperationException
s.
(Also, the designers might have made a interface ImmutableList
, to avoid a plethora of UnsupportedOperationException
s.)
You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.
if data.find('!masters') != -1:
with open('masters.txt', 'r') as f:
for line in f:
print line
sck.send('PRIVMSG ' + chan + " " + line + '\r\n')
If you're using an older version of python (pre 2.6) you'll have to have
from __future__ import with_statement
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T
According to the documentation you can decode JPEG/PNG images.
It should be something like this:
import tensorflow as tf
filenames = ['/image_dir/img.jpg']
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
images = tf.image.decode_jpeg(value, channels=3)
You can find a bit more info here
I've tried this and it works:
yourelement.next().val();
yourelement could be:
$('#elementIdName').next().val();
good luck!
I found the solution with this link : http://pixelsvsbytes.com/blog/2013/02/nice-web-fonts-for-every-browser/
Step by step method :
apt-get install ttfautohint
):ttfautohint --strong-stem-width=g neosansstd-black.ttf neosansstd-black.changed.ttf
I hope this will help.
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
I appreciate this question and all the info with it. I have something in mind that's kind of a question and an answer when it comes to String.Index.
I'm trying to see if there is an O(1) way to access a Substring (or Character) inside a String because string.index(startIndex, offsetBy: 1) is O(n) speed if you look at the definition of index function. Of course we can do something like:
let characterArray = Array(string)
then access any position in the characterArray however SPACE complexity of this is n
= length of string, O(n) so it's kind of a waste of space.
I was looking at Swift.String documentation in Xcode and there is a frozen public struct called Index
. We can initialize is as:
let index = String.Index(encodedOffset: 0)
Then simply access or print any index in our String object as such:
print(string[index])
Note: be careful not to go out of bounds`
This works and that's great but what is the run-time and space complexity of doing it this way? Is it any better?
I got the problem that the installation stopped by "$(^name) has stopped working" error. I have installed Java SE Development kit already, also set both SDK_HOME and JAVA_HOME that point to "C:\Program Files\Java\jdk1.7.0_21\"
My laptop installed with Windows 7 64 bits
So I tried to install the 32 bit version of Java SE Developement kit, set my JAVA_HOME to "C:\Program Files (x86)\Java\jdk1.7.0_21", restart and the installation worked OK.
I just found a solution for this.
for those who are not satisfied with the given answers can try this approach with flexbox
CSS
.myFlexContainer {
display: flex;
width: 100%;
}
.myFlexChild {
width: 100%;
display: flex;
/*
* set this property if this is set to column by other css class
* that is used by your target element
*/
flex-direction: row;
/*
* necessary for our goal
*/
flex-wrap: wrap;
height: 500px;
}
/* the element you want to put at the bottom */
.myTargetElement {
/*
* will not work unless flex-wrap is set to wrap and
* flex-direction is set to row
*/
align-self: flex-end;
}
HTML
<div class="myFlexContainer">
<div class="myFlexChild">
<p>this is just sample</p>
<a class="myTargetElement" href="#">set this to bottom</a>
</div>
</div>
DESCRIBE DATABASE NAME; you need to specify the name of the database and the results will include the data type of each attribute.
If you use has_many through, and want to alias:
has_many :alias_name, through: model_name, source: initial_name
This article about CSS image replacement for submit buttons could help.
"Using this method you'll get a clickable image when style sheets are active, and a standard button when style sheets are off. The trick is to apply the image replace methods to a button tag and use it as the submit button, instead of using input.
And since button borders are erased, it's also recommendable change the button cursor to
the hand shaped one used for links, since this provides a visual tip to the users."
The CSS code:
#replacement-1 {
width: 100px;
height: 55px;
margin: 0;
padding: 0;
border: 0;
background: transparent url(image.gif) no-repeat center top;
text-indent: -1000em;
cursor: pointer; /* hand-shaped cursor */
cursor: hand; /* for IE 5.x */
}
#replacement-2 {
width: 100px;
height: 55px;
padding: 55px 0 0;
margin: 0;
border: 0;
background: transparent url(image.gif) no-repeat center top;
overflow: hidden;
cursor: pointer; /* hand-shaped cursor */
cursor: hand; /* for IE 5.x */
}
form>#replacement-2 { /* For non-IE browsers*/
height: 0px;
}
<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>
In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic. I'd love some comments on the idea. Any traps I havent seen in it ?
You can use simple color resources, specified usually inside res/values/colors.xml
.
<color name="red">#ffff0000</color>
and use this via android:background="@color/red"
. This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via getResources().getColor(R.color.red)
.
You can also use any drawable resource as a background, use android:background="@drawable/mydrawable"
for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).
var express = require('express')
app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);
var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')
aws.config.update({
secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
region: 'us-east-1'
});
s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
dirname: "uploads",
bucket: "Your bucket name",
key: function (req, file, cb) {
console.log(file);
cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use
Date.now() for unique file keys
}
})
});
app.post('/upload', upload.single('photos'), function(req, res, next) {
console.log('Successfully uploaded ', req.file)
res.send('Successfully uploaded ' + req.file.length + ' files!')
})
Adding alternative base R approach, which remains fast under various cases.
rowsummean <- function(df) {
rowsum(df$speed, df$dive) / tabulate(df$dive)
}
Borrowing the benchmarks from @Ari:
10 rows, 2 groups
10 million rows, 10 groups
10 million rows, 1000 groups
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
If others who view this question only have a JSON string (not in an object), then you can put it into a HashMap
and still get the ObjectMapper
to work. The result
variable is your JSON string.
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
// Pretty-print the JSON result
try {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Update 2019 - Bootstrap 4.0.0
The pull-right
class is now float-right
in Bootstrap 4...
<div class="row">
<div class="col-12">One <input type="button" class="btn float-right" value="test"></div>
<div class="col-12">Two <input type="button" class="btn float-right" value="test"></div>
</div>
http://www.codeply.com/go/nTobetXAwb
It's also better to not align the ul list and use block elements for the rows.
Is float-right
still not working?
Remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right from working. In some cases, the util classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like a Bootstrap 4 .row, Card or Nav.
Also remember that text-right
still works on inline elements.
Bootstrap 4 align right examples
Bootstrap 3
Use the pull-right
class.
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
I was looking for a listing of macOS but found nothing, maybe this helps someone.
Output on macOS Catalina (10.15.7) using net5.0
# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER
# SpecialFolders (All)
SpecialFolder.AdminTools:
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning:
SpecialFolder.CommonAdminTools:
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory:
SpecialFolder.CommonDocuments:
SpecialFolder.CommonMusic:
SpecialFolder.CommonOemLinks:
SpecialFolder.CommonPictures:
SpecialFolder.CommonProgramFiles:
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonPrograms:
SpecialFolder.CommonStartMenu:
SpecialFolder.CommonStartup:
SpecialFolder.CommonTemplates:
SpecialFolder.CommonVideos:
SpecialFolder.Cookies:
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History:
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources:
SpecialFolder.MyComputer:
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos:
SpecialFolder.NetworkShortcuts:
SpecialFolder.PrinterShortcuts:
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86:
SpecialFolder.Programs:
SpecialFolder.Recent:
SpecialFolder.Resources:
SpecialFolder.SendTo:
SpecialFolder.StartMenu:
SpecialFolder.Startup:
SpecialFolder.System: /System
SpecialFolder.SystemX86:
SpecialFolder.Templates:
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows:
I have replaced my username with $USER.
Code Snippet from pogosama.
foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
string commonAppData = Environment.GetFolderPath(f);
Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();
This seems to work, although still a bit verbose (I'd like something shorter still):
@BeforeClass
public static void beforeClass() {
System.setProperty("some.property", "<value>");
}
// Optionally:
@AfterClass
public static void afterClass() {
System.clearProperty("some.property");
}
In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".
It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini
file by setting MaxAllowedContentLength
to the required value.
For eg. following will allow upto 300 mb requests
MaxAllowedContentLength=314572800
Hope it will help someone!
There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.
a = 0
b = 10
c = None
### Common approach that can cause a problem
if not a:
print(f"Answer is not found. Answer is {str(a)}.")
else:
print(f"Answer is: {str(a)}.")
if not b:
print(f"Answer is not found. Answer is {str(b)}.")
else:
print(f"Answer is: {str(b)}")
if not c:
print(f"Answer is not found. Answer is {str(c)}.")
else:
print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.
Answer is: 10.
Answer is not found. Answer is None.
### Safer approach
if a is None:
print(f"Answer is not found. Answer is {str(a)}.")
else:
print(f"Answer is: {str(a)}.")
if b is None:
print(f"Answer is not found. Answer is {str(b)}.")
else:
print(f"Answer is: {str(b)}.")
if c is None:
print(f"Answer is not found. Answer is {str(c)}.")
else:
print(f"Answer is: {str(c)}.")
Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.
For multiple datetime columns with no header, and a lot of columns, say my datetime fields are in columns 36 and 38, and I want them read in as character fields:
data<-read.csv("test.csv", head=FALSE, colClasses=c("V36"="character","V38"="character"))
you can use the each
function:
var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
alert(key)
});
it has several nice shortcuts/tricks: check the gory details here
use this line, this worked for me
mongoose.set('useUnifiedTopology', true);
System apps installed /system/app/ or /system/priv-app. Other apps can be installed in /data/app or /data/preload/.
Connect to your android mobile with USB and run the following commands. You will see all the installed packages.
$ adb shell
$ pm list packages -f
Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'
add this to your .h file
#import <MessageUI/MFMailComposeViewController.h>
Add MessageUI.framework to your project file
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
Delegate method is as shown below
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
With ECMAScript 2015 you can export and import multiple classes like this
class Person
{
constructor()
{
this.type = "Person";
}
}
class Animal{
constructor()
{
this.type = "Animal";
}
}
module.exports = {
Person,
Animal
};
then where you use them:
const { Animal, Person } = require("classes");
const animal = new Animal();
const person = new Person();
In case of name collisions, or you prefer other names you can rename them like this:
const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");
const animal = new OtherAnimal();
const person = new OtherPerson();
I've been looking around for this, but then I realize, damn my website uses php!!! Why not use the trim function on the text input and play with the max length....
Here is a possible solution too for those using php: http://ideone.com/PsTaI
<?php
$s = "In the beginning there was a tree.";
$max_length = 10;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
echo $s;
?>
Please try this one works for me:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:layout_gravity="center"
android:maxHeight="60dp"
android:scaleType="fitCenter"
android:src="@drawable/icon"
/>
If you've to support IE7, a more compatible solution is:
/* only the cells with no cell before (aka the first one) */
td {
padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
padding-left: 0;
}
Also works fine with li
; general sibling selector ~
may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.
If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.
But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.
Open the file using Notepad++ and check the "Encoding" menu, you can check the current Encoding and/or Convert to a set of encodings available.
You can use plenty of things.
<audio>
tag:Here is the official W3C specification for the audio tag.
Usage:
<audio controls>
<source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
type='audio/mp4'>
<!-- The next two lines are only executed if the browser doesn't support MP4 files -->
<source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
type='audio/ogg; codecs=vorbis'>
<!-- The next line will only be executed if the browser doesn't support the <audio> tag-->
<p>Your user agent does not support the HTML5 Audio element.</p>
</audio>
Or, if you want to support older browsers, you can use many of the free audio flash players available. Such as:
Note: I'm not sure which are the best ones, as I have never used one (yet).
UPDATE: As mentioned in another answer's comment, you are using XHTML 1.0 Transitional. You might be able to get <audio>
to work with some hack.
UPDATE 2: I just remembered another way to do play audio. This will work in XHTML!!! This is fully standards-compliant.
You use this JavaScript:
var aud = document.createElement("iframe");
aud.setAttribute('src', "http://yoursite.com/youraudio.mp4"); // replace with actual file path
aud.setAttribute('width', '1px');
aud.setAttribute('height', '1px');
aud.setAttribute('scrolling', 'no');
aud.style.border = "0px";
document.body.appendChild(aud);
This is my answer to another question.
UPDATE 3: To customise the controls, you can use something like this.
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
And it will execute with /bin/bash.
You should open text files using rU
so newlines are properly transformed, see http://docs.python.org/library/functions.html#open. This way there's no need to check for \r\n
.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
Hope this will help.
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: flex;
align-items: center;
justify-content: center;
}
row {
width: 100%;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:
sudo vi /etc/apt/sources.list
and added the following lines:
deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main
If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:
sudo apt-get update
sudo apt-get install build-essential
Hopefully this will help someone who had the same problem that I did.
Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".
aView.center = CGPoint(x: 200, Y: 200)
jQuery now has the .one()
function that limits any given event (such as "submit") to one occurrence.
Example:
$('#myForm').one('submit', function() {
$(this).find('input[type="submit"]').attr('disabled','disabled');
});
This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.
Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.
Note 2: Per gorelog, using attr('disabled','disabled')
will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;')
instead.
Single line:
${str:${#str}-1:1}
Now:
echo "${str:${#str}-1:1}"
Delete the .metadata
folder in your workspace.
If you mean using an attribute selector, sure, why not:
[data-role="page"] {
/* Styles */
}
There are a variety of attribute selectors you can use for various scenarios which are all covered in the document I link to. Note that, despite custom data attributes being a "new HTML5 feature",
browsers typically don't have any problems supporting non-standard attributes, so you should be able to filter them with attribute selectors; and
you don't have to worry about CSS validation either, as CSS doesn't care about non-namespaced attribute names as long as they don't break the selector syntax.
string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);
Something like this?
Perhaps you should handle the case of missing code :
...
string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);
if (ix != -1)
{
string code = myString.Substring(ix + toBeSearched.Length);
// do something here
}
A ternary will suffice. change:
gotdata = dlist[1]
to
gotdata = dlist[1] if len(dlist) > 1 else 'null'
this is a shorter way of expressing
if len(dlist) > 1:
gotdata = dlist[1]
else:
gotdata = 'null'
Sounds like you're looking for the time_ago_in_words
method (or distance_of_time_in_words
), from ActiveSupport. Call it like this:
<%= time_ago_in_words(timestamp) %>
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
That is usually all that you need to do...
Are you sure that after 20 minutes, the reason that the session is being lost is from being idle though...
There are many reasons as to why the session might be cleared. You can enable event logging for IIS and can then use the event viewer to see reasons why the session was cleared...you might find that it is for other reasons perhaps?
You can also read the documentation for event messages and the associated table of events.
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
Tried all the combinations here, but this worked for me:
mysqldump -u root -p --default-character-set=utf8mb4 [DATABASE TO BE COPIED NAME] > [NEW DATABASE NAME]
In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...
The simplest solution is this:
$date = '07/28/2010';
$newdate = date('Y-m-d', strtotime($date));
if you are running into problems with this on cocoapods v25 / Xcode 5
The Pods Xcode project now sets the ONLY_ACTIVE_ARCH build setting to YES in the Debug configuration. You will have to set the same on your project/target, otherwise the build will fail.
UPDATE Make sure you have latest gems / cocoapods
You will want to rebuild project using Pod Install to rebuild project.
To be more precise, I would use nanoTime()
method rather than currentTimeMillis()
:
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
In Java 8 (output format is ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Guava Stopwatch:
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
You can use proxytunnel:
proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000
and then you can do this:
openssl s_client -connect localhost:7000 -showcerts
Hope this can help you!
Postgres allows:
UPDATE dummy
SET customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
FROM /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;
This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.
Given the interface:
public interface IAnything {
int i;
void m1();
void m2();
void m3();
}
This is how Java actually sees it:
public interface IAnything {
public static final int i;
public abstract void m1();
public abstract void m2();
public abstract void m3();
}
So you can leave some (or all) of these abstract
methods unimplemented, just as you would do in the case of abstract
classes extending another abstract
class.
When you implement
an interface
, the rule that all interface
methods must be implemented in the derived class
, applies only to concrete class
implementation (i.e., which isn't abstract
itself).
If you indeed plan on creating an abstract class
out of it, then there is no rule that says you've to implement
all the interface
methods (note that in such a case it is mandatory to declare the derived class
as abstract
)
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
If using the .NET 2.0 (or later) framework you can use the CopyFromScreen()
method detailed here:
http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.
SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Its tested in all version of IE, Chrome, FF & Safari
// JavaScript code
<script type="text/javascript">
<!-- begin hiding
function expandSELECT(sel) {
sel.style.width = '';
}
function contractSELECT(sel) {
sel.style.width = '100px';
}
// end hiding -->
</script>
// Html code
<select name="sideeffect" id="sideeffect" style="width:100px;" onfocus="expandSELECT(this);" onblur="contractSELECT(this);" >
<option value="0" selected="selected" readonly="readonly">Select</option>
<option value="1" >Apple</option>
<option value="2" >Orange + Banana + Grapes</option>
There are a few possible ways to do this:
PYTHONPATH
to a colon-separated list of directories to search for imported modules.sys.path.append('/path/to/search')
to add the names of directories you want Python to search for imported modules. sys.path
is just the list of directories Python searches every time it gets asked to import a module, and you can alter it as needed (although I wouldn't recommend removing any of the standard directories!). Any directories you put in the environment variable PYTHONPATH
will be inserted into sys.path
when Python starts up.site.addsitedir
to add a directory to sys.path
. The difference between this and just plain appending is that when you use addsitedir
, it also looks for .pth
files within that directory and uses them to possibly add additional directories to sys.path
based on the contents of the files. See the documentation for more detail.Which one of these you want to use depends on your situation. Remember that when you distribute your project to other users, they typically install it in such a manner that the Python code files will be automatically detected by Python's importer (i.e. packages are usually installed in the site-packages
directory), so if you mess with sys.path
in your code, that may be unnecessary and might even have adverse effects when that code runs on another computer. For development, I would venture a guess that setting PYTHONPATH
is usually the best way to go.
However, when you're using something that just runs on your own computer (or when you have nonstandard setups, e.g. sometimes in web app frameworks), it's not entirely uncommon to do something like
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
Not the exception handling mechanism, But you can use the signal() mechanism that is provided by the C.
> man signal
11 SIGSEGV create core image segmentation violation
Writing to a NULL pointer is probably going to cause a SIGSEGV signal
Apparently, your class "Format" is involved in the problem. Check your declaration of this class, especially if you did it inside another class you probably forgot the @implementation or something similar.
Just move align="center" to de form tag
<form align="center" action="advsearcher.php" method="get">
Search this website:<input type="text" name="search" />
<input type="submit" value="Search"/>
</form>
Here is the easiest way I've seen. Note: Make sure you have "@Html.AntiForgeryToken()" in your View
$("a.markAsDone").click(function (event) {
event.preventDefault();
var sToken = document.getElementsByName("__RequestVerificationToken")[0].value;
$.ajax({
url: $(this).attr("rel"),
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: { '__RequestVerificationToken': sToken, 'id': parseInt($(this).attr("title")) }
})
.done(function (data) {
//Process MVC Data here
})
.fail(function (jqXHR, textStatus, errorThrown) {
//Process Failure here
});
});
There's another solution that I find useful, especially when I want to plot multiple subsets of the same object:
myplot<-ggplot(df)+geom_line(aes(Value1, Value2, group=ID, colour=ID))
myplot %+% subset(df, ID %in% c("P1","P3"))
myplot %+% subset(df, ID %in% c("P2"))
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".
I run into the same problem today, but unfortunately Andy's solution didn't work for me. In Spring Boot 1.2.1.RELEASE it's even easier, but you have to be aware of a few things.
Here is the interesting part from my application.yml
:
oauth:
providers:
google:
api: org.scribe.builder.api.Google2Api
key: api_key
secret: api_secret
callback: http://callback.your.host/oauth/google
providers
map contains only one map entry, my goal is to provide dynamic configuration for other OAuth providers. I want to inject this map into a service that will initialize services based on the configuration provided in this yaml file. My initial implementation was:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
private Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
After starting the application, providers
map in OAuth2ProvidersService
was not initialized. I tried the solution suggested by Andy, but it didn't work as well. I use Groovy in that application, so I decided to remove private
and let Groovy generates getter and setter. So my code looked like this:
@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {
Map<String, Map<String, String>> providers = [:]
@Override
void afterPropertiesSet() throws Exception {
initialize()
}
private void initialize() {
//....
}
}
After that small change everything worked.
Although there is one thing that might be worth mentioning. After I make it working I decided to make this field private
and provide setter with straight argument type in the setter method. Unfortunately it wont work that. It causes org.springframework.beans.NotWritablePropertyException
with message:
Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Cannot access indexed value in property referenced in indexed property path 'providers[google]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Bean property 'providers[google]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Keep it in mind if you're using Groovy in your Spring Boot application.
Close the modal with universal $().hide()
method:
$('#product-options').hide();
You can try this click event
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
Name_txt.Text = row.Cells["First Name"].Value.ToString();
Surname_txt.Text = row.Cells["Last Name"].Value.ToString();
If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).
Most web applications don't use impersonation / delegation, and hence don't have this problem.
See this MSDN article for more information.
In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.
In one line and probably faster then arr.indexOf(Math.max.apply(Math, arr))
:
var a = [0, 21, 22, 7];_x000D_
var indexOfMaxValue = a.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);_x000D_
_x000D_
document.write("indexOfMaxValue = " + indexOfMaxValue); // prints "indexOfMaxValue = 2"
_x000D_
Where:
iMax
- the best index so far (the index of the max element so far, on the first iteration iMax = 0
because the second argument to reduce()
is 0
, we can't omit the second argument to reduce()
in our case)x
- the currently tested element from the arrayi
- the currently tested indexarr
- our array ([0, 21, 22, 7]
)About the reduce()
method (from "JavaScript: The Definitive Guide" by David Flanagan):
reduce() takes two arguments. The first is the function that performs the reduction operation. The task of this reduction function is to somehow combine or reduce two values into a single value, and to return that reduced value.
Functions used with reduce() are different than the functions used with forEach() and map(). The familiar value, index, and array values are passed as the second, third, and fourth arguments. The first argument is the accumulated result of the reduction so far. On the first call to the function, this first argument is the initial value you passed as the second argument to reduce(). On subsequent calls, it is the value returned by the previous invocation of the function.
When you invoke reduce() with no initial value, it uses the first element of the array as the initial value. This means that the first call to the reduction function will have the first and second array elements as its first and second arguments.
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:
All these points need review and adjusting but after this it works like charm.
Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<annotationProcessors/>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
Edit 2019:
I think fork is a copy of other repository but with your account modification. for example, if you directly clone other repository locally, the remote object origin is still using the account who you clone from. You can't commit and contribute your code. It is just a pure copy of codes. Otherwise, If you fork a repository, it will clone the repo with the update of your account setting in you github account. And then cloning the repo in the context of your account, you can commit your codes.
// Captura datos usando metodo GET en la url colocar index.html?hola=chao
const $_GET = {};
const args = location.search.substr(1).split(/&/);
for (let i=0; i<args.length; ++i) {
const tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
console.log(`>>${$_GET['hola']}`);
}//::END if
}//::END for
Find out Year - Month- Day between two Days in Orale Sql
select
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
from dual;
I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.
http://technet.microsoft.com/en-us/library/bb490986.aspx
Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.
I. Plain XSLT 1.0 solution:
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()" name="split">
<xsl:param name="pText" select="."/>
<xsl:if test="string-length($pText)">
<xsl:if test="not($pText=.)">
<br />
</xsl:if>
<xsl:value-of select=
"substring-before(concat($pText,';'),';')"/>
<xsl:call-template name="split">
<xsl:with-param name="pText" select=
"substring-after($pText, ';')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
produces the wanted, corrected result:
123 Elm Street<br />PO Box 222<br />c/o James Jones
II. FXSL 1 (for XSLT 1.0):
Here we just use the FXSL template str-map
(and do not have to write recursive template for the 999th time):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
<xsl:import href="str-dvc-map.xsl"/>
<testmap:testmap/>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
<xsl:call-template name="str-map">
<xsl:with-param name="pFun" select="$vTestMap"/>
<xsl:with-param name="pStr" select=
"'123 Elm Street;PO Box 222;c/o James Jones'"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="replace" mode="f:FXSL"
match="*[namespace-uri() = 'testmap']">
<xsl:param name="arg1"/>
<xsl:choose>
<xsl:when test="not($arg1=';')">
<xsl:value-of select="$arg1"/>
</xsl:when>
<xsl:otherwise><br /></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:
123 Elm Street<br/>PO Box 222<br/>c/o James Jones
III. Using XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="text()">
<xsl:for-each select="tokenize(.,';')">
<xsl:sequence select="."/>
<xsl:if test="not(position() eq last())"><br /></xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on this XML document:
<t>123 Elm Street;PO Box 222;c/o James Jones</t>
the wanted, correct result is produced:
123 Elm Street<br />PO Box 222<br />c/o James Jones
First, you should probably use SYSDATETIME()
if you're looking for more precision.
To format your data with milliseconds, try CONVERT(varchar, SYSDATETIME(), 121)
.
For other formats, check out the MSDN page on CAST
and CONVERT
.
It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
No, you would need to give the do function in the constructor and the do function in the prototype different names.
Am I using the wrong method? What is the correct method I should be using?
Yes, this method java.net.URLEncoder.encode wasn't made for converting " " to "20%" according to spec (source).
The space character " " is converted into a plus sign "+".
Even this is not the correct method, you can modify this to: System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));
have a nice day =).
If you want to use SVG files as React components to perform customizations and do not use create-react-app, do the following:
yarn add --dev @svgr/webpack
webpack.config.js
...
module: {
rules: [
...
// SVG loader
{
test: /\.svg$/,
use: ['@svgr/webpack'],
}
],
},
...
import SomeImage from 'path/to/image.svg'
...
<SomeImage width={100} height={50} fill="pink" stroke="#0066ff" />
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Use grep:
grep -wE "string1|String2|...." file_name
Or you can use:
echo string | grep -wE "string1|String2|...."
Two steps:
- Generate the log
- Load Gmail to send the log
.
Generate the log
File generateLog() {
File logFolder = new File(Environment.getExternalStorageDirectory(), "MyFolder");
if (!logFolder.exists()) {
logFolder.mkdir();
}
String filename = "myapp_log_" + new Date().getTime() + ".log";
File logFile = new File(logFolder, filename);
try {
String[] cmd = new String[] { "logcat", "-f", logFile.getAbsolutePath(), "-v", "time", "ActivityManager:W", "myapp:D" };
Runtime.getRuntime().exec(cmd);
Toaster.shortDebug("Log generated to: " + filename);
return logFile;
}
catch (IOException ioEx) {
ioEx.printStackTrace();
}
return null;
}
Load Gmail to send the log
File logFile = generateLog();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile));
intent.setType("multipart/");
startActivity(intent);
References for #1
~~
For #2 - there are many different answers out there for how to load the log file to view and send. Finally, the solution here actually worked to both:
- load Gmail as an option
- attaches the file successfully
Big thanks to https://stackoverflow.com/a/22367055/2162226 for the correctly working answer
I just had a jaw-drop moment - Termux allows you to install NodeJS on an Android device!
It seems to work for a basic Websocket Speed Test I had on hand. The http served by it can be accessed both locally and on the network.
There is a medium post that explains the installation process
Basically: 1. Install termux 2. apt install nodejs 3. node it up!
One restriction I've run into - it seems the shared folders don't have the necessary permissions to install modules. It might just be a file permission thing. The private app storage works just fine.
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
in template
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
if my_list = [['a','b','c'], ['d','e','f']]
, you can use {{ my_list|index:x|index:y }}
in template to get my_list[x][y]
It works fine with "for"
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1
and 1st Jan 1900 00:00
equals 1
. So 11th June 2009 17:30
is about 39975.72917
.
If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.
So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss
, then it should be possible to achieve what you want.
Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).
You need to iterate your list and call String#trim
for searching:
String search = "A";
for(String str: myList) {
if(str.trim().contains(search))
return true;
}
return false;
OR if you want to perform ignore case search, then use:
search = search.toLowerCase(); // outside loop
// inside the loop
if(str.trim().toLowerCase().contains(search))
You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
echo '<a href="http://www.whatever.com/' . $param . '">Click Here</a>';
Notice that I escaped the double quotes inside my first example using a backslash.
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
A general answer involves using a Manager
object. Adapted from the docs:
from multiprocessing import Process, Manager
def f(d):
d[1] += '1'
d['2'] += 2
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
d[1] = '1'
d['2'] = 2
p1 = Process(target=f, args=(d,))
p2 = Process(target=f, args=(d,))
p1.start()
p2.start()
p1.join()
p2.join()
print d
Output:
$ python mul.py
{1: '111', '2': 6}
I am not sure I got you but this might be what you are looking for:
SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid
This would get you the amounts sums in case there are multiple payment rows for each invoice
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
I don't see why there is a encapsulation of a while...
Use
//Use the appropriate start and end...
for(int rowIndex = 0, e = 65536; i < e; ++i){
if(rowIndex >= dataColLinker.size()) {
dataColLinker.add(value);
} else {
dataColLinker.set(rowIndex, value);
}
}
To have a cron executed on Sunday you can use either of these:
5 8 * * 0
5 8 * * 7
5 8 * * Sun
Where 5 8
stands for the time of the day when this will happen: 8:05.
In general, if you want to execute something on Sunday, just make sure the 5th column contains either of 0
, 7
or Sun
. You had 6
, so it was running on Saturday.
The format for cronjobs is:
+---------------- minute (0 - 59)
| +------------- hour (0 - 23)
| | +---------- day of month (1 - 31)
| | | +------- month (1 - 12)
| | | | +---- day of week (0 - 6) (Sunday=0 or 7)
| | | | |
* * * * * command to be executed
You can always use crontab.guru as a editor to check your cron expressions.
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
Error: Default Activity Not Found
I solved this way
Run>>Edit Configuration >>Android Application >> Enter the path of your default
activity class in "Launch" Edit Box.
I've looked through all of the answers, and I don't think anyone mentions this possibility at all, and I'm not sure why.
If you want utmost simplicity and speed, at a minor cost, then to me it seems to make sense to store a random number against each row in the DB. Just create an extra column, random_number
, and set it's default to RAND()
. Create an index on this column.
Then when you want to retrieve a row generate a random number in your code (PHP, Perl, whatever) and compare that to the column.
SELECT FROM tbl WHERE random_number >= :random LIMIT 1
I guess although it's very neat for a single row, for ten rows like the OP asked you'd have to call it ten separate times (or come up with a clever tweak that escapes me immediately)
Since strptime
returns a datetime object which has tzinfo
attribute, We can simply replace it with desired timezone.
>>> import datetime
>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'
I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.
([System.Object[]](gci c:\pstback\ -Filter *.pst |
? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count
It still doesn't return zero if empty, but testing '-lt 1' works.
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
Vertical tab was used to speed up printer vertical movement. Some printers used special tab belts with various tab spots. This helped align content on forms. VT to header space, fill in header, VT to body area, fill in lines, VT to form footer. Generally it was coded in the program as a character constant. From the keyboard, it would be CTRL-K.
I don't believe anyone would have a reason to use it any more. Most forms are generated in a printer control language like postscript.
@Talvi Wilson noted it used in python '\v'.
print("hello\vworld")
Output:
hello
world
The above output appears to result in the default vertical size being one line. I have tested with perl "\013" and the same output occurs. This could be used to do line feed without a carriage return on devices with convert linefeed to carriage-return + linefeed.
For me placing my fonts folder as per location specified in bootstrap.css solved the problem
Mostly its fonts folder should be in parent directory of bootstrap.css file .
I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .
The bug has already been solved by bootstrap
for those looking for a way to mock POST
HttpServletRequest with Json payload, the below is in Kotlin, but the key take away here is the DelegatingServetInputStream when you want to mock the request.getInputStream
from the HttpServletRequest
@Mock
private lateinit var request: HttpServletRequest
@Mock
private lateinit var response: HttpServletResponse
@Mock
private lateinit var chain: FilterChain
@InjectMocks
private lateinit var filter: ValidationFilter
@Test
fun `continue filter chain with valid json payload`() {
val payload = """{
"firstName":"aB",
"middleName":"asdadsa",
"lastName":"asdsada",
"dob":null,
"gender":"male"
}""".trimMargin()
whenever(request.requestURL).
thenReturn(StringBuffer("/profile/personal-details"))
whenever(request.method).
thenReturn("PUT")
whenever(request.inputStream).
thenReturn(DelegatingServletInputStream(ByteArrayInputStream(payload.toByteArray())))
filter.doFilter(request, response, chain)
verify(chain).doFilter(request, response)
}
Short answer: Both are needed.
I feel like the right answer was given but minimally. Yeah generally unset() is best for "speed", but if you want to reclaim memory immediately (at the cost of CPU) should want to use null.
Like others mentioned, setting to null doesn't mean everything is reclaimed, you can have shared memory (uncloned) objects that will prevent destruction of the object. Moreover, like others have said, you can't "destroy" the objects explicitly anyway so you shouldn't try to do it anyway.
You will need to figure out which is best for you. Also you can use __destruct() for an object which will be called on unset or null but it should be used carefully and like others said, never be called directly!
see:
http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
It appears that you are using the default route which is defined as this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The key part of that route is the {id}
piece. If you look at your action method, your parameter is k
instead of id
. You need to change your action method to this so that it matches the route parameter:
// change int k to int id
public ActionResult DetailsData(int id)
If you wanted to leave your parameter as k, then you would change the URL to be:
http://localhost:7317/Employee/DetailsData?k=4
You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):
<connectionStrings>
<add name="EmployeeContext"
connectionString="Server=.;Database=mytry;integrated security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
For instance, this HTML element:
<input type="text" value="Name:">
has 2 attributes (type
and value
).
Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.
For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes
property of that object.
When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:
<input id="the-input" type="text" value="Name:">
the corresponding DOM node will have id
,type
, and value
properties (among others):
The id
property is a reflected property for the id
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id
is a pure reflected property, it doesn't modify or limit the value.
The type
property is a reflected property for the type
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type
isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">
, then theInput.getAttribute("type")
gives you "foo"
but theInput.type
gives you "text"
.
In contrast, the value
property doesn't reflect the value
attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value
property will reflect this change. So if the user inputs "John"
into the input box, then:
theInput.value // returns "John"
whereas:
theInput.getAttribute('value') // returns "Name:"
The value
property reflects the current text-content inside the input box, whereas the value
attribute contains the initial text-content of the value
attribute from the HTML source code.
So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue
property, which is a pure reflection of the value
attribute:
theInput.value // returns "John"
theInput.getAttribute('value') // returns "Name:"
theInput.defaultValue // returns "Name:"
There are several properties that directly reflect their attribute (rel
, id
), some are direct reflections with slightly-different names (htmlFor
reflects the for
attribute, className
reflects the class
attribute), many that reflect their attribute but with restrictions/modifications (src
, href
, disabled
, multiple
), and so on. The spec covers the various kinds of reflection.
sed -e 's/Here\(.*\)String/\1/'
Check out SSMS Tool Pack. It works in Management Studio 2005 and 2008. There is an option to generate insert statements which I've found helpful moving small amounts of data from one system to another.
With this option you will have to script out the DDL separately.
I was able to sort this out using Gorgando's fix, but instead of moving imports away, I commented each out individually, built the app, then edited accordingly until I got rid of them.
You can check Observable represented by Rxjs, lets you return more than one value.
Print integer in hex-value with zero-padding (if needed) :
int intValue = 1234;
Console.WriteLine("{0,0:D4} {0,0:X3}", intValue);
https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.
The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch
around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.
I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.
I use the jQuery clueTip plugin for this.
In C#, float
is an alias for System.Single
(a bit like int
is an alias for System.Int32
).
Use this ^[a-zA-Z0-9_]*$
See here for more info.
I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.
Without using itertools
:
In Python 3 you can use yield from
to add a subset generator method to buit-in set
class:
class SetWithSubset(set):
def subsets(self):
s1 = []
s2 = list(self)
def recfunc(i=0):
if i == len(s2):
yield frozenset(s1)
else:
yield from recfunc(i + 1)
s1.append(s2[ i ])
yield from recfunc(i + 1)
s1.pop()
yield from recfunc()
For example below snippet works as expected:
x = SetWithSubset({1,2,3,5,6})
{2,3} in x.subsets() # True
set() in x.subsets() # True
x in x.subsets() # True
x|{7} in x.subsets() # False
set([5,3]) in x.subsets() # True - better alternative: set([5,3]) < x
len(x.subsets()) # 32
As Scobal's post implies, the datepicker is looking for a Date object - not just a string! So, to modify your example code to do what you want:
var queryDate = new Date('2009/11/01'); // Dashes won't work
$('#datePicker').datepicker('setDate', queryDate);
Here's a simple extension method that returns a slice as a new array:
public static T[] Slice<T>(this T[] arr, uint indexFrom, uint indexTo) {
if (indexFrom > indexTo) {
throw new ArgumentOutOfRangeException("indexFrom is bigger than indexTo!");
}
uint length = indexTo - indexFrom;
T[] result = new T[length];
Array.Copy(arr, indexFrom, result, 0, length);
return result;
}
Then you can use it as:
byte[] slice = foo.Slice(0, 40);
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
It's probably a permissions issue but you need to make sure to try these steps to troubleshoot:
sa
and add the net use
and net use /delete
commands before and afterRemember to undo any changes (especially running as sa
). If nothing else works, you can try to change the bulk load into a scheduled task, running on the database server or another server that has bcp installed.
You could do this:
(Note! This is CSS3 and the browser support = good!! )
p {
text-overflow: ellipsis; /* will make [...] at the end */
width: 370px; /* change to your preferences */
white-space: nowrap; /* paragraph to one line */
overflow:hidden; /* older browsers */
}
I recommend creating a .json file (ex: config.json). Then paste all of your json object and format it. And thus you will be able to remove all of that things that is breaking your json-object, and get clean copy-paste json-object.
The simplest way I have found is to just set the container name in the docker-compose.yml
See container_name documentation. It is applicable to docker-compose v1+. It works for container to container, not from the host machine to container.
services:
dns:
image: phensley/docker-dns
container_name: affy
Now you should be able to access affy
from other containers using the container name. I had to do this for multiple redis servers in a development environment.
NOTE The solution works so long as you don't need to scale. Such as consistant individual developer environments.
You may run into this problem if your database is set to autogrow the log & you end up with lots of virtual log files.
Run DBCC LOGINFO('databasename')
& look at the last entry, if this is a 2 then your log file wont shrink. Unlike data files virtual log files cannot be moved around inside the log file.
You will need to run BACKUP LOG and DBCC SHRINKFILE several times to get the log file to shrink.
For extra bonus points run DBBC LOGINFO in between log & shirks
Navigate to Sublime Text>Preferences>Browse Packages. You should see a file tree.
In the Packages folder, you should see
Theme - Default > Default.sublime-theme (substitute Default for your theme name)
Open that file and find the "class": "sidebar_label: entry and add "font.size".
example:
{
"class": "sidebar_label",
"color": [0, 0, 0],
"font.bold": false,
"font.size": 14
},
To implement the fix, first expand out the existing web.config compilation section that looks like this by default:
<compilation debug="true" targetFramework="4.5"/>
Once expanded, I then added the following new configuration XML as I was instructed:
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</assemblies>
The final web.config tags should look like this:
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</assemblies>
</compilation>
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
make folder and name it foe example download open note pad and insert this code
only change http://www.google.com/aa.zip to your file and save it to m.php for example
chamod the php file to 666 and the folder download to 777
<?php
define('BUFSIZ', 4095);
$url = 'http://www.google.com/aa.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>
finally from your browser enter to these URL http://www.example.com/download/m.php
you will see in download folder the file download from other server
thanks
One possibility:
myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});
Please note that filter
creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray
with the new reference. Use with caution.
In case of a 2D array (matrix), you can use:
[val, idx] = max(A, [], 2);
The idx part will contain the column number of containing the max element of each row.
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
My understanding is that arrays are stored more efficiently (i.e. as contiguous blocks of memory vs. pointers to Python objects), but I am not aware of any performance benefit. Additionally, with arrays you must store primitives of the same type, whereas lists can store anything.
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
This worked for me
You could define a clone function.
I use this one :
function goclone(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
clone[prop] = goclone(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = goclone(A);
It doesn't copy the prototype, functions, and so on. But you should adapt it (and maybe simplify it) for you own need.
Go through each item of the array and sum values to previous values if they exist, if not just assign the value.
<?php
$array =
[
[
'a'=>1,
'b'=>1,
'c'=>1,
],
[
'a'=>2,
'b'=>2,
],
[
'a'=>3,
'd'=>3,
]
];
$result = array_reduce($array, function($carry, $item) {
foreach($item as $k => $v)
$carry[$k] = $v + ($carry[$k] ?? 0);
return $carry;
}, []);
print_r($result);
Output:
Array
(
[a] => 6
[b] => 3
[c] => 1
[d] => 3
)
Or just loop through each sub array, and group the values for each column. Eventually summing them:
foreach($array as $subarray)
foreach($subarray as $key => $value)
$grouped[$key][] = $value;
$sums = array_map('array_sum', $grouped);
If you don't mind using 3rd party libraries, AOL's cyclops-react lib, disclosure::I am a contributor, has a ExceptionSoftener class that can help here.
s.filter(softenPredicate(a->a.isActive()));
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
Add a key in your info.plist
file UIViewControllerBasedStatusBarAppearance
and set it to YES
.
In viewDidLoad method of your ViewController add a method call:
[self setNeedsStatusBarAppearanceUpdate];
Then paste the following method in viewController
file:
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
UIKit
uses the topLayoutGuide & bottomLayoutGuide which is UIView
propertyiOS11+ uses safeAreaLayoutGuide which is also UIView
property
Enable Safe Area Layout Guide check box from file inspector.
Safe areas help you place your views within the visible portion of the overall interface.
In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
Use safe areas as an aid to laying out your content like UIButton
etc.
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.
The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active
print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones
Height of home indicator container is 34 points.
Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.
You can set constraints with respective of self.view.safeAreaLayoutGuide
as-
ObjC:
self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
Swift:
demoView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
} else {
NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
}
Thanks to John Saunders post above which gave me an idea to look into Error window. I was bagging all day my head and I was looking at Output window for any error.
In my case the culprit was ISerializable. I have a DataContract class with DataMember property of type Exception. You cannot have any DataMember of type which has ISerializable keyword. In this Exception has ISerializable as soon as I removed it everything worked like a charm.
The only solution worked for me was @Tiago Gouvêa answer, after adding it android and emulator commands worked fine, but sdkmanager command was not working so I have added one extra line to his solution:
nano ~/.bash_profile
Add lines:
export ANDROID_HOME=/YOUR_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH
Be explicit about the tuples.
[(i, j) for (i, j) in enumerate(mylist)]
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
Format MySQL datetime with PHP
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";
Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode
when using the v2 YAML format.
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
A solution for me was to create a UILabel
and add it to the UIButton
as a subview. Finally I added a constraint to center it within the button.
UILabel * myTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
myTextLabel.text = @"Some Text";
myTextLabel.translatesAutoresizingMaskIntoConstraints = false;
[myButton addSubView:myTextLabel];
// Add Constraints
[[myTextLabel centerYAnchor] constraintEqualToAnchor:myButton.centerYAnchor].active = true;
[[myTextLabel centerXAnchor] constraintEqualToAnchor:myButton.centerXAnchor].active = true;
new Date("2016-3-17").valueOf()
will return a long epoch
See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:
>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)
If you take something like this:
>>> firstvalue = mvv_list[0].mvv
Out: 1
You will get the mvv
value. If you want all the information of the array you can take something like this:
>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]
But if you try the same for the other column, you get:
>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'
This happens because count
is a built-in method. And the column has the same name as count
. A workaround to do this is change the column name of count
to _count
:
>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]
But this workaround is not needed, as you can access the column using the dictionary syntax:
>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]
And it will finally work!
In IIS 10, we use a similar solution to Drew's approach, i.e.:
using System;
using System.Web;
namespace Common.Web.Modules.Http
{
/// <summary>
/// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
/// </summary>
public class CustomHeaderModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
public void Dispose() { }
/// <summary>
/// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
/// that occurs just before ASP.NET sends HTTP headers to the client.
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server", "MyServer");
}
}
}
And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:
<system.webServer>_x000D_
<modules>_x000D_
<!--Use http module to remove/customize IIS "Server" header-->_x000D_
<add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />_x000D_
</modules>_x000D_
</system.webServer>
_x000D_
IMPORTANT NOTE1: This solution needs an application pool set as integrated;
IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);